Loops
While
#![allow(unused)] fn main() { let mut number = 3; while number != 0 { println!("{}!", &number); number -= 1; } }
3!
2!
1!
While let
Same as while but we get a variable back if the assertion matches, so we can access top
directly below:
fn main() { let mut stack = Vec::new(); stack.push(1); stack.push(2); stack.push(3); while let Some(top) = stack.pop() { println!("{}", top); } }
3
2
1
For destructure
Also using an enumerate to get back the index
#![allow(unused)] fn main() { let v = vec!['a', 'b', 'c']; for (index, value) in v.iter().enumerate() { println!("{} is at index {}", value, index); } }
a is at index 0
b is at index 1
c is at index 2
For Range
#![allow(unused)] fn main() { for number in (1..4).rev() { println!("{}!", number); } println!("LIFTOFF!!!"); }
3!
2!
1!
LIFTOFF!!!
For iter
Print all the items in the array
#![allow(unused)] fn main() { let a = [10, 20, 30, 40, 50]; for e in a.iter() { println!("The value is: {}", e); } }
The value is: 10
The value is: 20
The value is: 30
The value is: 40
The value is: 50
For .len()
Print just the iterator
#![allow(unused)] fn main() { let x = [1, 5, 10, 20]; for i in 0..x.len() { println!("{}", i); } }
0
1
2
3
For iter enumerate over string as bytes
This example searches for a b' '
denoting a space to return to first word
fn first_word(s: &str) -> &str { let bytes = s.as_bytes(); for (i, &item) in bytes.iter().enumerate() { if item == b' ' { return &s[0..i]; } } &s[..] } fn main() { let mut s = String::from("Coolioio one yo"); // deref coercion let x = first_word(&mut s); println!("{}", x); }
Coolioio
Break
Break can be suffixed with an expression to return the result of the expression.
#![allow(unused)] fn main() { let mut counter = 0; let x = loop { counter += 1; if counter == 10 { break counter * 2; } }; println!("{}", x); }
20
Break return
If the semicolon is removed from the end of the loop, we can return the result from the loop expression.
fn looper() -> i32 { let mut counter = 0; loop { counter += 1; if counter == 10 { break counter * 2; } } } fn main() { let x = looper(); println!("The result is {}!", x); }
The result is 20!