Functions
A function is defined using the fn keyword.
function = "fn" IDENT "(" [ params ] ")" [ "->" type ] "{" block "}" ;
params = param { "," param } ;
param = IDENT ":" type ;
Function Signature
Parameters MUST have explicit type annotations.
If a return type is specified, the function body MUST produce a value of that type.
If no return type is specified, the function returns ().
fn add(x: i32, y: i32) -> i32 {
x + y
}
fn do_nothing() {
// implicitly returns ()
}
Entry Point
A program MUST have a function named main.
The main function MUST return either i32 or (). When it returns i32, that value becomes the program's exit code. When it returns (), the exit code is 0.
fn main() -> i32 {
42 // exit code is 42
}
Recursion
Functions MAY call themselves recursively.
fn factorial(n: i32) -> i32 {
if n <= 1 { 1 }
else { n * factorial(n - 1) }
}
fn main() -> i32 {
factorial(5) // 120
}
Function Visibility
Functions MAY call any function defined in the same module, regardless of definition order.
fn main() -> i32 {
helper() // can call function defined below
}
fn helper() -> i32 {
42
}