Trusted answers to developer questions

What are mutable variables in Rust?

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

In Rust, variables are immutable by default, which means that their values cannot be changed. If a new value is assigned to a variable that was declared with the let keyword, the program won’t compile:

fn main() {
let a = 10; // 'a' is an immutable variable
a = 5; // Cannot change the value of 'a'
}

This feature of Rust is handy when the programmer knows that a variable being declared is not supposed to change throughout its lifetime.

Mutable variables

When a variable does need to change its value during run-time, the mut keyword can be used to indicate that the variable is mutable:

fn main() {
let mut a = 10; // 'a' is a mutable variable
println!("a = {}", a);
a = 5; // Value of 'a' can now be changed
println!("a = {}", a);
}

Shadowing

There are certain instances where an immutable variable may need to transform its value temporarily and then become immutable again. This is known as shadowing.

fn main() {
let a = 10; // 'a' is an immutable variable
// The first 'a' is shadowed by this new one:
let a = a * a;
// 'a' is still immutable
println!("a = {}", a);
}

Shadowing also allows us to change the variable’s type (e.g., from string to integer) and its value:

fn main() {
let string = "123"; // 'string' is an immutable variable
let string = string.len();
println!("string length = {}", string);
}

RELATED TAGS

immutable
constant
data type
shadowing
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?