Variables and Mutability

Variables and Mutability

Learn about variables, mutability, constants, and shadowing in Rust.

15 min read4 learning objectives

What You'll Learn

  • Understand immutability by default in Rust
  • Learn how to create mutable variables
  • Differentiate between variables and constants
  • Master variable shadowing

Variables and Mutability

In Rust, variables are immutable by default. This is one of Rust's key features that helps you write safer, more predictable code.

Declaring Variables

Use the let keyword to declare variables:

The code above creates an immutable variable x with the value 5. If you try to change it, Rust will give you a compile-time error.

Mutable Variables

To make a variable mutable, use the mut keyword:

Constants

Constants are similar to immutable variables, but with key differences:

Constants vs Variables:

  • Constants use const instead of let
  • You must annotate the type (e.g., u32)
  • Constants can be declared in any scope, including global
  • Constants must be set to a constant expression, not computed at runtime
  • Naming convention: SCREAMING_SNAKE_CASE

Shadowing

Rust allows you to declare a new variable with the same name as a previous variable. This is called shadowing:

Shadowing vs Mutability:

Shadowing is different from marking a variable as mut. With shadowing, you're creating a new variable, which means you can even change its type:

Practice Exercise

Try to predict what this code will output: