They allow us to group and reuse statements, with the possibility to return values
main
function (no function prototypes, unlike C)
functions
fn
keyword, followed by the function's name
and parameters (placed in ()
){}
Note: Rust uses snake case names (like a_b
, my_function
...);
cargo clippy
will get angry if you don't do the samefunctions
Here is the definition and usage of a function that prints "Hello World!"
:
fn main() {
hello_world();
}
fn hello_world() {
println!("Hello World!"):
}
functions
param: Type
functions
fn main() {
let a = 6;
let b = 8;
pythagoras(a, b); // Prints "a^2 + b^2 = 100"
}
fn pythagoras(a: i32, b: i32) {
println!("a^2 + b^2 = {}", a*a + b*b);
}
functions
We often need a function to return a value after its execution. To do so:
-> Type
return
keyword with a value;return
keyword and the colon at the end of the line
functions
Let's change the previous example:
fn main() {
let a = 6;
let b = 8;
let res = pythagoras(a, b);
println!("a^2 + b^2 = {res}");
}
fn pythagoras(a: i32, b: i32) -> i32 {
a*a + b*b
}
functions
As in other programming languages, we can use recursion to perform tasks:
fn main(){
let n = 4;
let res = fibonacci(n);
println!("{res}"); // Prints "5"
}
//Function that calculates the nth Fibonacci number
fn fibonacci(n: u64) -> u64 {
if n <= 1 {
return 1;
}
fibonacci(n - 1) + fibonacci(n - 2)
}