Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Functions are defined using the fn keyword and can be placed inside various scopes:

Here is a function that takes no argument and returns nothing:

Hello!

11.1.1Definition order

The order of definition of functions does not matter. We can use a function that is not yet defined:

Hello!

11.1.2Nested function

Functions can be defined inside other functions:

Hello!

However, they cannot be accessed outside their definition’s scope:

[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:

[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:

Function with no parameter.
Function with a u8 parameter (16).