Control flow
[control_flow.incl: fix (P1)](https://github.com/john-cd/rust_howto/issues/540)
If else
fn main() { let number = 3; let result: u8 = if number < 5 { println!("Condition was true"); 5 // `if` is an expression } else { println!("Condition was false"); 6 }; println!("{}", result); }
Also else if <cond> { ... }
Loop
fn main() { let mut counter = 0; let result = loop { counter += 1; if counter == 10 { break counter * 2; // `continue` and loop labels also exist: // https://doc.rust-lang.org/book/ch03-05-control-flow.html } }; println!("{}", result); }
While
fn main() { let mut number = 5; while number != 0 { println!("{number}!"); number -= 1; } }
For
fn main() { let a = [10, 20, 30, 40, 50]; for element in a { println!("the value is: {element}"); } // Range - generates all numbers in sequence // starting from one number and ending before another number. for number in (1..4).rev() { // reverse enumeration println!("{number}!"); } }
[control_flow: add description (P1)](https://github.com/john-cd/rust_howto/issues/541)