Control Flow
Section |
---|
Control flow |
If else |
Loop |
While |
For |
TODO
If else
#![allow(unused)] fn main() { let number = 3; let result = if number < 5 { // condition must return a bool; `if` is an expression println!("condition was true"); 5 } else { println!("condition was false"); 6 }; println!("{}", result); }
Also else if <cond> { ... }
Loop
#![allow(unused)] 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
#![allow(unused)] fn main() { let mut number = 5; while number != 0 { println!("{number}!"); number -= 1; } }
For
#![allow(unused)] 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}!"); } }
TODO: add description