Expressions
Expression: combinaison de valeurs (calcul arithmétique, booleen, etc.) retournant (exprimant) une valeur.
Exemple d'expressions arithmétiques, booléennes et litérales:
fn main() { // Integer addition println!("1 + 2 = {}", 1u32 + 2); // Integer subtraction println!("1 - 2 = {}", 1i32 - 2); // Short-circuiting boolean logic println!("true AND false is {}", true && false); println!("true OR false is {}", true || false); println!("NOT true is {}", !true); // Bitwise operations println!("0011 AND 0101 is {:04b}", 0b0011u32 & 0b0101); println!("0011 OR 0101 is {:04b}", 0b0011u32 | 0b0101); println!("0011 XOR 0101 is {:04b}", 0b0011u32 ^ 0b0101); println!("1 << 5 is {}", 1u32 << 5); println!("0x80 >> 2 is 0x{:x}", 0x80u32 >> 2); // Use underscores to improve readability! println!("One million is written as {}", 1_000_000u32); }
À la différence de langages comme C/C++, en Rust, les blocs peuvent "renvoyer" une expression, ce qui le rapproche d'un langage fonctionnel, comme dans l'exemple ci-dessous:
fn main() { let y = 8; let x = 6 + { let x = 7; if y > 5 { 5 * x } else { y + x } }; println!("{x} and {y}"); }
ou encore ici:
fn main() { let x = 5u32; let y = { let x_squared = x * x; let x_cube = x_squared * x; // This expression will be assigned to `y` x_cube + x_squared + x }; let z = { // The semicolon suppresses this expression and `()` is assigned to `z` 2 * x; }; println!("x is {:?}", x); println!("y is {:?}", y); println!("z is {:?}", z); }
La valeur ()
correspond à une valeur vide et est appelée unit
.