Function Concept
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;
}
Homework: Open this example live and run it: functions
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.
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.
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