Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
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.

Variables, Data Types and Constants

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

The shortcut

Ask two questions of every value: "Will it change while the program runs?" and "Is it known before the program runs?"

Three values in the library programStep 1 of 4
  1. The maximum loan length

    Never changes, known in advance: const MAX_LOAN_DAYS: u32 = 21;

The trap is adding mut "just in case". It hides which values change and invites mistakes. The compiler even warns when a mut variable is never actually changed.

Drills

Answer fast — trust the rule.

quick drill

What happens when you compile let copies = 2; copies = 3;?

quick drill

Which line is a valid constant?

quick drill

With no annotation, what type does let pages = 320; get?

quick drill

After let title = "The Salt Road"; let title = title.len();, what is true?

Remember

  • let is immutable by default; let mut can be reassigned; const needs a type and never changes.
  • Ask: will it change? Known in advance? Default to plain let.
  • Trap: sprinkling mut everywhere, and confusing shadowing (new variable) with mutation (same variable).

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

Explainlet, mut, shadowing or const?

The library program stores a maximum loan length that never changes, a count of books on loan that goes up and down, and a title read as text that you then turn into its length. Explain which Rust tool fits each and why.