Functions, Statements, and Expressions
Functions, Statements, and Expressions
Rust is an expression-oriented language. Almost every construct evaluates to a value.
Statements vs. Expressions
- Statements: Instructions that perform an action and do not return a value. Ending an expression with a semicolon
;turns it into a statement returning unit(). - Expressions: Evaluate to a resulting value. Omission of the final semicolon returns the expression value.
fn add(a: i32, b: i32) -> i32 {
a + b // No semicolon: implicit return
}
fn compute_block(factor: i32) -> i32 {
let result = {
let base = 100;
base * factor // Expression evaluated and bound to result
};
result
}
fn main() {
println!("Add: {}", add(10, 20));
println!("Compute block: {}", compute_block(3));
}