Beginner Fundamentals
Functions
Functions group reusable logic. You declare them with fn, give each parameter a type, and optionally specify a return type.
Defining a function
fn greet() {
println!("Hello from a function!");
}
fn main() {
greet();
}
Typed parameters
Every parameter must have an explicit type.
fn print_sum(a: i32, b: i32) {
println!("Sum: {}", a + b);
}
fn main() {
print_sum(4, 7); // Sum: 11
}
Return values
Use -> to declare the return type. The last expression, written without a semicolon, becomes the return value.
fn square(n: i32) -> i32 {
n * n // no semicolon: this is the returned value
}
fn main() {
let result = square(5);
println!("{}", result); // 25
}
Early return
You can also return early with the return keyword.
fn abs(n: i32) -> i32 {
if n < 0 {
return -n;
}
n
}
Remember: adding a semicolon to the final expression turns it into a statement, which returns the unit type () instead of your value.