Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

immutable
constant
data type
shadowing

What are mutable variables in Rust?

Educative Answers Team

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 ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring