Search⌘ K

Variable and Parameter Scope

Explore how variable and parameter scopes operate within Rust functions to improve your coding practices. Learn about block-level scoping, the visibility of variables, and how shadowing allows multiple variables with the same name in different scopes. This lesson helps you understand how to manage variable lifetimes and scope effectively in Rust programming.

We'll cover the following...

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

Rust 1.40.0
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:

Rust 1.40.0
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 ...