官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 屯留县| 屏东市| 盐山县| 阳东县| 隆回县| 霍城县| 三亚市| 叙永县| 汝南县| 兴义市| 焦作市| 星子县| 房产| 仁化县| 辽阳县| 惠东县| 北辰区| 连平县| 固安县| 内乡县| 中超| 松潘县| 武陟县| 台中县| 嘉义县| 温宿县| 阿坝县| 元谋县| 顺平县| 华宁县| 普宁市| 白河县| 遂溪县| 新昌县| 新泰市| 弥渡县| 吐鲁番市| 北京市| 腾冲县| 碌曲县| 红原县|