Mutable Variables
Part of the Fundamentals section of Coddy's Rust journey — lesson 9 of 75.
In Rust, variables are immutable by default. This means that once you assign a value to a variable, you cannot change that value. However, you can make a variable mutable by using the mut keyword when declaring the variable.
For example:
let x = 5; // x is immutable
let mut y = 10; // y is mutableIn this example, x is immutable, so you cannot change its value after it's initialized. On the other hand, y is mutable, so you can change its value later in the code.
y = 20; // This is allowed because y is mutable
x = 15; // This will cause an error because x is immutableChallenge
BeginnerDeclare a mutable variable named add and assign it the value 13.
Change the value from 13 to 16.
Cheat sheet
In Rust, variables are immutable by default. To make a variable mutable, use the mut keyword:
let x = 5; // immutable variable
let mut y = 10; // mutable variableYou can reassign values to mutable variables:
y = 20; // allowed - y is mutable
x = 15; // error - x is immutableTry it yourself
#[allow(unused_assignments)] // Don't delete this line
fn main() {
// Initialize variable add
// Change value from 13 to 16
// Don't change the line below
println!("add = {}", add);
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 33Variables Part 2
Type DeclarationNaming ConventionsType InferenceRecap - Initialize VariablesType Casting9Loops
For Over SeriesWhile LoopBreakContinueNested LoopLoop LabelsInfinite LoopRecap - Dynamic Input