0
0
Rustprogramming~5 mins

Mutable variables in Rust

Choose your learning style9 modes available
Introduction

Mutable variables let you change the value stored in them after you create them. This helps when you want to update information as your program runs.

When you want to keep track of a score that changes during a game.
When you need to update a counter in a loop.
When you want to store user input that can change.
When you want to modify a value based on conditions.
When you want to build a value step-by-step.
Syntax
Rust
let mut variable_name = initial_value;

Use mut right after let to make a variable mutable.

Without mut, variables are read-only and cannot be changed.

Examples
This creates a mutable variable count starting at 0, then changes it to 5.
Rust
let mut count = 0;
count = 5;
This variable name is not mutable, so trying to change it will cause an error.
Rust
let name = "Alice";
// name = "Bob"; // This will cause an error because name is not mutable
Here, temperature starts at 20 and then increases by 5.
Rust
let mut temperature = 20;
temperature = temperature + 5;
Sample Program

This program shows a mutable variable score starting at 0, then changing to 10, printing both values.

Rust
fn main() {
    let mut score = 0;
    println!("Initial score: {}", score);
    score = 10;
    println!("Updated score: {}", score);
}
OutputSuccess
Important Notes

Remember to use mut only when you need to change the variable.

Rust helps prevent bugs by making variables immutable by default.

Summary

Mutable variables let you change values after creating them.

Use let mut to declare a mutable variable.

Without mut, variables cannot be changed.