Beginner Fundamentals

Variables

In Rust you declare variables with the let keyword. By default, a variable is immutable, meaning its value cannot change after assignment.

Declaring variables

fn main() {
    let age = 30;
    let name = "Alice";
    println!("{} is {}", name, age);
}

Rust infers the type from the value, so you rarely need to write it. You can still annotate it explicitly:

fn main() {
    let count: i32 = 10;
    let pi: f64 = 3.14;
    println!("{} {}", count, pi);
}

Immutable by default

Once assigned, an immutable variable keeps its value. Trying to reassign it is a compile error.

fn main() {
    let score = 100;
    // score = 200; // error: cannot assign twice to immutable variable
    println!("{}", score);
}

This default helps prevent accidental changes and makes code easier to reason about. When you do need a value to change, you opt in with mut, covered next.