11.2.1Accepting parameters¶
Each function parameter is declared with its type, separated by a colon. Multiple parameters are separated by commas.
Here is an example with one integer parameter:
fn foo(n: u8) {
println!("The number is {n}");
}
foo(5);The number is 5
Here is an example with two parameters:
fn foo(n: u8, c: char) {
println!("The number is {n}.");
println!("The character is {c}.");
}
foo(5, 'Z');The number is 5.
The character is Z.
11.2.2Parameter mutability¶
Any parameter can be declared mutable in order to allow its modification inside the function:
fn foo(mut n: u8) {
n += 10;
println!("The number is {n}.");
}
foo(5);The number is 15.
11.2.3Returning a value¶
The most used form for returning a value is by writing an expression at the
end of the function, without a semicolon. The type of the returned value
must be declared using the -> symbol:
fn foo() -> u8 {
let x = 2;
x + 4
}
foo()6Since the if statement can also be used to build an expression, we can
use it to return a value conditionally:
fn foo(n: u8) -> u8 {
if n > 100 {
n / 2
} else {
n
}
}
foo(128)6411.2.4The return keyword¶
The return keyword is used to leave the function. It can be used anywhere
inside the function’s scope:
fn foo(n: i8) {
if n < 5 {
return;
}
println!("The number is {n}.");
}
foo(-3);
foo(6);The number is 6.
The return keyword can also return a value:
fn foo() -> u8 {
let x = 2;
return x + 4;
}
foo()6