Skip to content

Latest commit

 

History

History
34 lines (27 loc) · 847 Bytes

07. functions.md

File metadata and controls

34 lines (27 loc) · 847 Bytes

Functions

  • Functions are declared with the keyword fn
  • When using arguments, you must declare data types.
  • By default functions return empty tuple (). If you want to return a value, return type must be specified after ->
//Hello world function
fn main() {
    println!("Hello, world!");
}

//Function with arguments 
fn print_sum(a: i8, b: i8) {
    println!("sum is: {}", a + b);
}

//Returning
fn plus_one(a: i32) -> i32 {
    a + 1 //no ; means an expression, return a+1
}

fn plus_two(a: i32) -> i32 {
    return a + 2; //return a+2 but bad practice, 
    //should use only on conditional returnes, except it's last expression 
}

// ⭐️ Function pointers, Usage as a Data Type
let b = plus_one;
let c = b(5); //6

let b: fn(i32) -> i32 = plus_one; //same, with type inference
let c = b(5); //6