...

/

Variable and Parameter Scope

Variable and Parameter Scope

We'll cover the following...

Let’s look at one of our examples from earlier:

Press + to interact
fn say_apples(apples: i32) {
println!("I have {} apples", apples);
}
fn main() {
say_apples(10);
}

We have apples in the parameter list for say_apples. This means that we’re allowed to use the name apples inside the body of the say_apples function. However, we can’t use it inside the body of the main function. This program will not compile:

Press + to interact
fn say_apples(apples: i32) {
println!("I have {} apples", apples);
}
fn main() {
say_apples(10);
println!("apples == {}", apples);
}

Variable names are only visible inside a certain scope. When you have the function ...