Skip to the workspace
Pebellslearn by building
Introduction to Rust  ›  Lesson

Variables, Data Types and Constants

Variables, DataTypes and Constants 12 minA Rust variable is immutable unless marked mut, every value has a type the compiler knows, and a const is a fixed, typed value that never changes.

rust / Variables, Data Types and Constants

Explore each scene at your own pace.

01 · The rule

The rule

Variables, Data Types and Constants

A Rust variable is immutable unless marked mut, every value has a type the compiler knows, and a const is a fixed, typed value that never changes.

Choose mutable bindings, immutable bindings and compile-time constants deliberately.

The library program needs to remember things: how many books are on loan, the longest a loan may last, the title someone just searched for. Rust gives you three tools for that, and it expects you to say up front which values are allowed to change.

The rule

let is fixed, let mut can change, const never changes.

let binds a name to a value, immutably by default.

let on_loan = 3;
on_loan = 4; // error: cannot assign twice to immutable variable

let mut allows reassignment.

let mut on_loan = 3;
on_loan += 1; // fine, now 4

const is a value fixed for the whole program. It must have a written type, and by convention its name is in capitals.

const MAX_LOAN_DAYS: u32 = 21;

Every value has a type. Usually the compiler infers it: let pages = 320; becomes i32, the default integer, and let rating = 4.5; becomes f64, the default float. You can write the type yourself with a colon: let pages: u32 = 320;. Once set, a variable's type cannot change.

Shadowing is a second let with the same name. It creates a new variable, which may even have a new type:

let title = "The Salt Road";
let title = title.len(); // now a number: 13
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.