Functions
We've already discussed functions a bit, but let's do a bit more digging. As of right now, we've only seen the main
function. But let's create another function:
fn main() {
println!("Hello, world!");
another_function();
}
fn another_function() {
println!("Another function.");
}
This will print out:
Hello world!
Another function.
As alluded to the section Hello World, Rust functions can have parameters but the parameters must have a type.
fn main() {
another_function(5);
}
fn another_function(x: i32) {
println!("The value of x is: {}", x);
}
If a function has a return value, then it's type also must be declared.
fn plus_one(x: i32) -> i32 {
x + 1
}
fn main() {
let x = plus_one(5);
println!("The value of x is: {}", x);
}
You might have noticed that x + 1
didn't have a semicolon after it. That is because it is an expression and not a statement. Per the Rust book:
Statements are instructions that perform some action and do not return a value. Expressions evaluate to a resulting value. Let’s look at some examples.
Let's clarify that with some sample code:
fn main() {
let x = 5; // x is a statement
// `let y =` is a statement but the contents of the {} are an expression
let y = {
let x = 3; // statement
x + 1 // expression
};
println!("The value of y is: {}", y);
}
Last updated