Variables are fundamental building blocks in Rust programming. They allow you to store and manipulate data throughout your program. Understanding how variables work in Rust is crucial for writing efficient and safe code.
In Rust, variables are declared using the let
keyword. By default, variables are immutable, meaning their values cannot be changed after initialization.
let x = 5;
// x = 10; // This would cause a compilation error
To create mutable variables, use the mut
keyword. This allows you to change the value of the variable after its initial assignment.
let mut y = 5;
y = 10; // This is valid
Rust has a strong type system with type inference. The compiler can often deduce the type of a variable based on its usage. However, you can also explicitly specify the type:
let inferred_type = 5; // i32 is inferred
let explicit_type: u32 = 5; // Explicitly typed as u32
Rust allows variable shadowing, which means you can declare a new variable with the same name as a previous variable. This is useful for changing the type of a variable or performing transformations while keeping the same name.
let z = 5;
let z = z + 1; // Shadows the previous 'z'
let z = z * 2; // Shadows again
Variables in Rust have block scope. They are valid from the point of declaration until the end of the block in which they are declared.
{
let inner_var = 42;
// inner_var is valid here
}
// inner_var is not valid here
While not variables in the strict sense, constants are related and worth mentioning. They are declared using the const
keyword and must always have an explicit type annotation.
const MAX_POINTS: u32 = 100_000;
To deepen your understanding of Rust variables, explore these related topics:
By mastering variables in Rust, you'll build a solid foundation for more advanced concepts in the language. Remember, Rust's approach to variables contributes significantly to its memory safety and concurrency features.