Rust Functions
A function is a named recipe. You write the steps once, give them a name, and then use the name whenever you need those steps, as many times as you like. You already know one function, main. Now let us write our own.
fn greet() {
println!("Hello there!");
println!("Welcome to Rust.");
}
fn main() {
greet();
greet();
}Hello there! Welcome to Rust. Hello there! Welcome to Rust.
The function is defined with fn, a name, round brackets and a body in curly brackets. Writing greet(); calls the function: Rust jumps into it, runs its steps, and comes back. It does not matter whether a function is written above or below main.
Parameters: giving a function inputs
A function becomes much more useful when it can work on different values each time. The values it receives are called parameters, listed in the round brackets. In Rust you must always write each parameter's type:
fn greet(name: &str, times: u32) {
for _ in 0..times {
println!("Hi, {}!", name);
}
}
fn main() {
greet("Kabir", 2);
greet("Zoya", 1);
}Hi, Kabir! Hi, Kabir! Hi, Zoya!
The underscore in for _ in means we do not need the counter's value; we only want to repeat.
Return values: getting an answer back
A function can also give a value back to whoever called it. The type of that value comes after an arrow ->. The last expression in the body, written without a semicolon, is the value returned:
fn area(width: f64, height: f64) -> f64 {
width * height
}
fn is_adult(age: u32) -> bool {
age >= 18
}
fn main() {
let room = area(4.0, 3.5);
println!("The room is {} square metres", room);
println!("Is 20 an adult? {}", is_adult(20));
}The room is 14 square metres Is 20 an adult? true
The semicolon matters
This is the one detail that trips everybody up at first. width * height without a semicolon is an expression: it produces a value, which becomes the function's answer. Add a semicolon and it becomes a statement, which produces nothing, and the compiler will complain that the function promised an f64 but gave back nothing. If you ever see the error "mismatched types" pointing at the end of a function, look for a stray semicolon.
You can also leave a function early with return value;. That is handy inside an if, for example to stop as soon as the answer is known.
Practice exercises
- Write a function
square(n: i32) -> i32and use it to print the squares of 1 to 5. - Write
celsius_to_fahrenheit(c: f64) -> f64and convert 0, 37 and 100 degrees. - Add a semicolon after the last line of
areaand read the error and the hint.