Functions are reusable blocks of code. Rust emphasizes function declarations with explicit parameter and return types for clarity and safety.
Function Declaration
fnadd(a: i32, b: i32) ->i32 {
a + b
}
Breakdown:
fn keyword declares a function
Name: add
Parameters: (a: i32, b: i32) with types
Return type: -> i32
Last expression without semicolon is the return value
Parameters and Return Types
All parameters require type annotations. Return types aren't inferred:
fnmultiply(x: f64, y: f64) ->f64 {
x * y // No semicolon—this is the return value
}
fnprint_number(n: i32) {
// No return type means returns unit ()println!(\"Number: {}\", n);
} // Implicitly returns ()
Statements vs Expressions
Statements end with semicolons and don't return values: