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

  • Learning Rust
  • Paul Johnson Vesa Kaihlavirta
  • 420字
  • 2021-07-02 23:07:24

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.

主站蜘蛛池模板: 资中县| 陆丰市| 江门市| 青浦区| 石棉县| 龙井市| 嘉善县| 五莲县| 墨江| 屯门区| 岳池县| 凤阳县| 丽江市| 西乌珠穆沁旗| 武邑县| 赣州市| 黄大仙区| 昌江| 永安市| 柯坪县| 阳高县| 高台县| 凉山| 阿克陶县| 娄烦县| 通化市| 新乡市| 瑞金市| 泰兴市| 南靖县| 东丰县| 德钦县| 永川市| 新沂市| 湘乡市| 漳平市| 东乡| 文昌市| 台安县| 正阳县| 高碑店市|