Functions are defined using the fn keyword and can be placed inside
various scopes:
At global level.
Inside another function.
Inside an
impl(implementation) block of astruct(structure).Inside a
traitdefinition (see Traits chapter).
Here is a function that takes no argument and returns nothing:
fn foo() {
println!("Hello!");
}
foo();Hello!
11.1.1Definition order¶
The order of definition of functions does not matter. We can use a function that is not yet defined:
fn foo() {
foo2();
}
fn foo2() {
println!("Hello!");
}
foo();Hello!
11.1.2Nested function¶
Functions can be defined inside other functions:
fn foo() {
fn my_nested_fct() {
println!("Hello!");
}
my_nested_fct();
}
foo();Hello!
However, they cannot be accessed outside their definition’s scope:
fn foo() {
fn my_nested_fct() {
println!("Hello!");
}
}
my_nested_fct();[E0425] Error: cannot find function `my_nested_fct` in this scope
╭─[ command_5:1:1 ]
│
8 │ my_nested_fct();
│ ──────┬──────
│ ╰──────── not found in this scope
───╯11.1.3Function overloading¶
In Rust, function overloading is forbidden.
Here is an example with an overloading of a function foo(), rejected by
the compiler:
fn foo() {
println!("Function with no parameter.");
}
fn foo(n: u8) {
println!("Function with a u8 parameter ({n}).");
}
foo();[E0061] Error: this function takes 1 argument but 0 arguments were supplied
╭─[ command_6:1:1 ]
│
9 │ foo();
│ ─┬──┬
│ ╰───── error: this function takes 1 argument but 0 arguments were supplied
│ │
│ ╰── argument #1 of type `u8` is missing
│ │
│ ╰── help: provide the argument: `(/* u8 */)`
───╯To define the two functions we need to name them differently:
fn foo() {
println!("Function with no parameter.");
}
fn foo2(n: u8) {
println!("Function with a u8 parameter ({n}).");
}
foo();
foo2(16);Function with no parameter.
Function with a u8 parameter (16).