Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Functions

Function

  • any function used in main function must defined in the program (after or before main function)
  • type annotation of parameters is mandatory in function’s signature (i.e. what precedes function’s body).
  • functions can return a value if defined (by declaring their type):
    • the return value can be explicitly defined with return statement or
    • the last expression in a function is implicitly returned.
// `fn` <function_name> ( <input params> ) -> <return_type> { <body> }
fn main() {
    let x: i32 =  sum(5, 6);
    let y = number();

    println!("The number is {x}");  
    println!("The number is {}", y); 
}

fn sum(a: i32, b: i32) -> i32 {

    // the last expression in a function is implicitly returned
     a + b  
    }

fn number() -> i32 {

    // the explicitly defined return value 
    return 3 + 5;  
}