Functions in Rust
Functions are the building blocks of readable, maintainable code. In Rust, functions are declared using the fn keyword and follow a clear, consistent syntax.
Basic Function Syntax
Here's how you define a simple function in Rust:
fn greet() {
println!("Hello, world!");
}
To call this function, you simply write greet();
Functions with Parameters
Functions can take parameters, which must have type annotations:
fn greet_person(name: &str) {
println!("Hello, {}!", name);
}
Return Values
Functions can return values. The return type is declared after an arrow ->:
fn add(x: i32, y: i32) -> i32 {
x + y // Note: no semicolon here!
}
Multiple Parameters
You can have multiple parameters with different types:
fn calculate_rectangle_area(width: f64, height: f64) -> f64 {
width * height
}
Practice Time!
Try writing a function that:
- Takes two numbers as parameters
- Returns their sum
- Prints the result
fn main() {
let result = add_numbers(5, 3);
println!("The sum is: {}", result);
}
fn add_numbers(a: i32, b: i32) -> i32 {
a + b
}
Key Points to Remember
- Functions start with
fn - Parameter types must be declared
- Return types are declared with
-> - The last expression in a function is implicitly returned
- Early returns use the
returnkeyword - Function names use snake_case by convention
Now it's your turn to experiment with functions in the playground below!
Key Takeaways
- Functions are declared with
fnand can return values using->syntax - Rust functions must declare parameter types explicitly
- The last expression in a function body is implicitly returned (no
returnneeded) - Functions can return tuples to return multiple values
- Closures capture variables from their environment
Next Steps
Now that you can write functions, you're ready to learn about ownership and borrowing — the system that guarantees memory safety without a garbage collector. It's Rust's most distinctive feature, and understanding it makes every later concept click into place.
Next lesson
Ownership & Borrowing
Rust ownership explained — understand move semantics, borrowing rules, and how Rust guarantees memory safety without a garbage collector
25 min