Prematurely terminating a loop

Depending on the size of the data being iterated over within a loop, the loop can be costly on processor time. For example, say the server is receiving data from a data-logging application, such as measuring values from a gas chromatograph; over the entire scan, it may record roughly half a million data points with an associated time position.

For our purposes, we want to add all of the recorded values until the value is over 1.5 and once that is reached, we can stop the loop.

Sound easy? There is one thing not mentioned: there is no guarantee that the recorded value will ever reach over 1.5, so how can we terminate the loop if the value is reached?

We can do this in one of two ways. The first is to use a while loop and introduce a Boolean to act as the test condition. In the following example, my_array represents a very small subsection of the data sent to the server:

// 04/terminate-loop-1/src/main.rs
fn main() { let my_array = vec![0.6f32, 0.4, 0.2, 0.8, 1.3, 1.1, 1.7, 1.9]; let mut counter: usize = 0; let mut result = 0f32; let mut quit = false; while quit != true { if my_array[counter] > 1.5 { quit = true; } else { result += my_array[counter]; counter += 1; } } println!("{}", result); }

The result here is 4.4. This code is perfectly acceptable, if slightly long-winded. Rust also allows the use of the break and continue keywords (if you're familiar with C, they work in the same way).

Our code using break will be as follows:

// 04/terminate-loop-2/src/main.rs
fn main() { let my_array = vec![0.6f32, 0.4, 0.2, 0.8, 1.3, 1.1, 1.7, 1.9]; let mut result = 0f32; for(_, value) in my_array.iter().enumerate() { if *value > 1.5 { break; } else { result += *value; } } println!("{}", result); }

Again, this will give an answer of 4.4, indicating that the two methods used are equivalent.

If we replace break with continue in the preceding code example, we will get the same result (4.4). The difference between break and continue is that continue jumps to the next value in the iteration rather than jumping out, so if we had the final value of my_array as 1.3, the output at the end should be 5.7.

When using break and continue, always keep in mind this difference. While it may not crash the code, mistaking break and continue may lead to results that you may not expect or want.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset