In Rust, variables behave differently compared to many other programming languages.
By default, variables are immutable, meaning once you assign a value to a variable, you cannot change it. This is one of the core design choices of Rust that helps you write safer and more predictable programs.
In this tutorial, you will:
- Learn how to declare variables in Rust.
- Understand why variables are immutable by default.
- Explore how to make variables mutable with the
mutkeyword. - See examples of when to use immutable vs. mutable variables.
Declaring a Variable #
To declare a variable in Rust, you use the let keyword. For example:
fn main() {
let x = 5;
println!("The value of x is: {}", x);
}
Code language: Rust (rust)In this code:
let x = 5;declares a variable namedxwith the value5.println!is a macro that prints the value ofxto the screen.
Variables are Immutable by Default #
Let’s see what happens if you try to change the value of x:
fn main() {
let x = 5;
println!("The value of x is: {}", x);
x = 6; // This will cause an error!
println!("The value of x is: {}", x);
}
Code language: Rust (rust)If you run this, you’ll see an error similar to:
error[E0384]: cannot assign twice to immutable variable `x`Code language: Rust (rust)This happens because variables in Rust are immutable by default. You cannot change their values once assigned.
Making Variables Mutable #
If you need to change a variable’s value, you can make it mutable with the mut keyword:
fn main() {
let mut y = 10;
println!("The value of y is: {}", y);
y = 15; // This works now
println!("The value of y is: {}", y);
}
Code language: Rust (rust)In this example:
let mut y = 10;creates a mutable variable.- Later, we successfully update
yto15.
When to Use Immutable vs Mutable #
Immutable variables
- Default choice in Rust.
- Makes your code safer because values don’t change unexpectedly.
- Helps prevent bugs in large programs.
Mutable variables
- Use only when you really need to update a value.
- Examples: counters in a loop, tracking state that changes over time.
By encouraging immutability, Rust nudges you toward writing code that’s easier to reason about and less error-prone.
Try It Yourself #
- Declare an immutable variable and try reassigning it. Notice the compiler error.
- Change it to mutable with
mutand rerun your code. - Think about whether your variable really needs to be mutable.
Now you know how variables work in Rust, why immutability is the default, and when to use mut.