Knowledge Garden

Search

Search IconIcon to open search

Scope in Rust

Last updated Oct 31, 2022 Edit Source

# Scope in Rust

scope begins where it’s created and ends at the end of the block, and through nested blocks.

1
2
3
4
fn main(){
	let x = 5;
	
}

x is available through the entire block

variables can be shadowed vars are always local to their scope

1
2
3
4
5
6
7
8
fn main(){
	let x = 5;
	{
		let x = 99;
		println!("{}",x); // prints 99
	}
	println!("{}",x); // prints 5
}

you can also shadow vars in the same scope

1
2
3
4
5
fn main()
{
	let mut x = 5; // is mutable
	let x = x; // x is now immutable
}

compiler will often discard earlier changes for optimization