Rust Variables
A variable is a name attached to a value, so that you can use and reuse that value in your program. In Rust you create a variable with the let keyword.
Creating variables
fn main() {
let city = "Lisbon";
let population = 545_000;
let rainy = false;
println!("City: {}", city);
println!("Population: {}", population);
println!("Rainy today? {}", rainy);
}City: Lisbon
Population: 545000
Rainy today? false
Notice that we never wrote a type. Rust infers the type from the value: city is a string slice, population is an integer and rainy is a boolean. The underscore in 545_000 is just a visual separator — it does not change the number.
Variables are immutable by default
This is the first big surprise for newcomers: once a value is bound to a name, you cannot change it, unless you ask for that explicitly. This code does not compile:
fn main() {
let score = 10;
score = 20;
println!("{}", score);
}error[E0384]: cannot assign twice to immutable variable `score`
--> src/main.rs:3:5
|
2 | let score = 10;
| ----- first assignment to `score`
3 | score = 20;
| ^^^^^^^^^^ cannot assign twice to immutable variable
|
help: consider making this binding mutable
|
2 | let mut score = 10;
| +++Immutability by default makes programs easier to reason about: when you read let x = ..., you know x will keep that value.
Mutable variables with mut
Add mut after let when a value really needs to change:
fn main() {
let mut lives = 3;
println!("Lives at start: {}", lives);
lives = lives - 1;
println!("After falling into a pit: {}", lives);
lives += 2;
println!("After finding two hearts: {}", lives);
}Lives at start: 3
After falling into a pit: 2
After finding two hearts: 4
Note that mut lets you change the value, not the type. Assigning a string to lives would be an error.
Declaring with a type
You can write the type yourself after a colon. This is needed when Rust cannot guess, and it is useful to make your intent clear:
fn main() {
let width: u32 = 1920;
let ratio: f64 = 16.0 / 9.0;
let initial: char = 'R';
println!("{} px, ratio {:.3}, initial {}", width, ratio, initial);
}1920 px, ratio 1.778, initial R
You can also declare a variable first and give it a value later — as long as it is assigned before it is used:
let message;
message = "assigned later";Shadowing
You may declare a new variable with the same name as an old one. The new one shadows the previous one. Unlike mut, shadowing can even change the type:
fn main() {
let input = "42";
let input: i32 = input.parse().unwrap();
let input = input * 2;
println!("Result: {}", input);
}Result: 84
Each let input creates a brand-new variable. This is a common Rust pattern for transforming a value step by step without inventing names like input_str and input_num.
let mut |
Shadowing (let again) |
|
|---|---|---|
| Same variable? | Yes | No, a new one |
| Can change type? | No | Yes |
Needs mut? |
Yes | No |
Naming rules
- Names may contain letters, digits and underscores, but cannot start with a digit.
- Names are case sensitive (
totalandTotaldiffer). - Use
snake_case:first_name,max_speed. - Keywords such as
let,fnormatchcannot be used as names. - A name starting with
_(like_unused) tells the compiler not to warn when it is unused.
Test yourself
What happens if you assign a new value to a variable declared with plain let?
- The value changes
- A compile error
- A runtime panic
- The assignment is ignored
Which declaration allows the value to change later?
- let x = 5;
- const x = 5;
- let mut x = 5;
- let x: mut = 5;
Which feature lets you reuse a name with a different type?
- mut
- Shadowing with another
let - Casting with
as - It is not possible