0PricingLogin
Learn Rust Coding · Lesson

let and Mutability

Bindings and mut.

Binding Values with let

In Rust you create a variable with the let keyword. This binds a name to a value.

By default every binding is immutable — once you give it a value, you cannot change it.

fn main() {
    let x = 5;
    println!("The value of x is: {}", x);
}

Immutable by Default

Rust makes variables immutable on purpose. This prevents accidental changes and makes code easier to reason about.

Trying to reassign an immutable binding causes a compile error, not a runtime crash.

  • let x = 5; then x = 6; will not compile.
fn main() {
    let x = 5;
    // x = 6; // this would cause a compile error
    println!("x stays {}", x);
}

All lessons in this course

  1. let and Mutability
  2. Scalar Types
  3. Compound Types
  4. Shadowing
← Back to Learn Rust Coding