Sage-Code Laboratory
index<--

Function Concept

In programming a function is a named block of code designed to perform a particular task. Functions usually have one or more parameters and most function return one result. The function is a common way to create reusable code and split a larger problem into smaller parts.
function

Function Concept

Rust Functions

Example:

fn main() {
    //test function print_sum() with no result
    print_sum(5, 6); //call function
    print_sum(4, 4); //call function
    //test function call sum_of() two times
    println!("sum_of(5,6) = {}", sum_of(5,6));
    println!("sum_of(4,4) = {}", sum_of(4,4));
    //capture result in new variable z
    let z = sum_of(11, 12);
    println!("sum_of(11, 12): z = {}", z);
}
/* define function with side-effect */
fn print_sum(x: i32, y: i32) {
    println!("print_sum({},{}) = {}", x, y, x + y);
}
/* define function with result */
fn sum_of(x: i32, y: i32) -> i32 {
    return x + y;
}

Notes:

  1. In Rust we define a function using "fn" keyword then name of the function. The result type can be declared using symbol "->". In other languages we may use "=>".
  2. In the function body we can use return statement to create the function result and stop function execution in the same time.
  3. Result of a function, symbol "->" after function parameters and the return statement are both optional.

Homework: Open this example live and run it: functions

Variable Scope

In English the "scope" has two meanings:

This may confuse some for the meaning of "Variable Scope". We use the first meaning: The "scope" of a variable is the area or the block of code where the variable is visible and relevant.

Shadowing

All variables defined in outer scope are visible in the inner scope. We can hide a variable by rebinding the name to a new value using "let". In this case the external variable will be hidden or "shadowed". Variable shadowing can change the type and the value of the variable name.

Examples:

fn main() {
    //outer scope
    let x: i32 = 5;
    let y: u8 = 255;
    { // inner scope
        let x: i64 = 65536;
        println!("inner x = {}",x); // 65536
        println!("outer y = {}",y); // 255
    }
    println!("outer x = {}",x); // 5
}

Notes:

Homework: open this example and run it on-line: shadowing


Read next: Methods