- 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.
- Mastering ServiceStack
- Cross-platform Desktop Application Development:Electron,Node,NW.js,and React
- OpenCV for Secret Agents
- Hands-On GPU:Accelerated Computer Vision with OpenCV and CUDA
- 深入RabbitMQ
- Building Serverless Applications with Python
- 組態(tài)軟件技術(shù)與應(yīng)用
- Nginx Lua開發(fā)實(shí)戰(zhàn)
- Unity 2D Game Development Cookbook
- Spring Boot+MVC實(shí)戰(zhàn)指南
- HTML5移動(dòng)Web開發(fā)
- Developing Java Applications with Spring and Spring Boot
- Beginning C# 7 Hands-On:The Core Language
- 零基礎(chǔ)C語(yǔ)言學(xué)習(xí)筆記
- Swift從入門到精通 (移動(dòng)開發(fā)叢書)