YouTip LogoYouTip

Rust Loop

# Rust Loops Besides flexible conditional statements, Rust also features a well-designed loop structure. Experienced developers should be able to appreciate this. ### while Loop The while loop is the most typical conditional loop: ## Example fn main(){ let mut number =1; while number !=4{ println!("{}", number); number +=1; } println!("EXIT"); } Output: 123 EXIT As of the date this tutorial was written, Rust does not have a do-while loop, but `do` is a reserved keyword, so it might be used in future versions. In C, the for loop is controlled by a ternary statement, but Rust does not use this approach. You need to use a while loop instead: ## C Language int i; for(i =0; i <10; i++){ // loop body } ## Rust let mut i =0; while i <10{ // loop body i +=1; } ### for Loop The for loop is the most commonly used loop structure, often used to traverse a linear data structure (like an array). Here's a for loop traversing an array: ## Example fn main(){ let a =[10,20,30,40,50]; for i in a.iter(){ println!("Value: {}", i); } } Output: Value: 10Value: 20Value: 30Value: 40Value: 50 In this program, the for loop traverses array `a`. `a.iter()` represents the iterator for `a`. We won't elaborate further until we cover objects in a later chapter. Of course, you can also access array elements by index using a for loop: ## Example fn main(){ let a =[10,20,30,40,50]; for i in 0..5{ println!("a[{}] = {}", i, a); } } Output: a = 10 a = 20 a = 30 a = 40 a = 50 ### loop Loop Experienced developers have likely encountered situations where a loop cannot determine whether to continue at the beginning or end, and must be controlled from somewhere within the loop body. In such cases, we often implement an early exit from within a `while (true)` loop. Rust has a native infinite loop structure β€” the `loop`: ## Example fn main(){ let s =['R','U','N','O','O','B']; let mut i =0; loop{ let ch = s; if ch =='O'{ break; } println!("'{}'", ch); i +=1; } } Output: 'R' 'U' 'N' The `loop` can exit the entire loop and provide a return value to the outside using the `break` keyword, similar to `return`. This is a clever design, as `loop` is often used as a search tool. If something is found, you naturally want to return the result: ## Example fn main(){ let s =['R','U','N','O','O','B']; let mut i =0; let location =loop{ let ch = s; if ch =='O'{ break i; } i +=1; }; println!("Index of 'O' is {}", location); } Output: Index of 'O' is 3
← Os FstatOs Fchown β†’