Skip to main content

Variables in Rust

Ayesha
EditReport

Variables are used to store data in memory.

In Rust, variables are immutable by default, which means their values cannot be changed after creation.

Video Explanation​

Declaring a Variable​

fn main() {
let x = 10;
println!("{}", x);
}

Explanation​

  • let is used to declare a variable.
  • x is the variable name.
  • 10 is the value stored in the variable.
  • println!() prints the value.

Immutable Variables​

fn main() {
let x = 5;
// x = 6; ❌ Error
}

Rust does not allow changing immutable variables.

Mutable Variables​

To make a variable changeable, use mut.

fn main() {
let mut x = 5;
x = 10;

println!("{}", x);
}

Explanation​

  • mut means mutable.
  • Mutable variables can change their values.

Variable Shadowing​

Rust allows redeclaring variables using the same name.

fn main() {
let x = 5;
let x = x + 1;

println!("{}", x);
}

Output​

6

Shadowing creates a new variable with the same name.

Track Your Progress

Done with this topic? Mark it as complete to track your progress.

đŸ’Ŧ Discuss this page

Have a question or spot something confusing in "Variables in Rust"? Ask below — it's backed by GitHub Discussions, so maintainers get notified like any other GitHub activity.