MARY.WIN

RUSTY — BEGINNER — B02

Variables, types and
mutability

Learn what `let`, `mut` and a type annotation promise, and why Rust refuses a string where a number belongs.
Lesson 2 of 9 in Rust beginner track. Before you start: Lesson 1.

You set a counter, attempts, to 1, and on the next line you add one to it. In PHP, that runs. In Rust, the compiler stops with error[E0384]: cannot assign twice to immutable variable. The arithmetic is fine.

Rust wants you to say, on the line where the value is born, whether it will ever change.

This lesson covers let and mut, the basic types, char and what .len() counts, converting text to a number, shadowing, and the two text types in signatures, &str and String. It leaves out why owning text matters (ownership, in the main series) and keeping a failed conversion as a value (Lesson 7). It assumes Lesson 1. If you've ever met a PHP TypeError, you have the right instinct already.

Take a look at Example 1.

Example 1. The rejected counter (examples/compile-fail/f02_immutable.rs)

fn main() {
    let attempts = 1;
    attempts += 1;
    println!("{attempts}");
}

It doesn't compile, and that's the point. From the examples folder, hand it to the compiler:

TERMINAL
rustc --edition=2024 compile-fail/f02_immutable.rs
error[E0384]: cannot assign twice to immutable variable `attempts`
 --> compile-fail/f02_immutable.rs:3:5
  |
2 |     let attempts = 1;
  |         -------- first assignment to `attempts`
3 |     attempts += 1;
  |     ^^^^^^^^^^^^^ cannot assign twice to immutable variable
  |
help: consider making this binding mutable
  |
2 |     let mut attempts = 1;
  |         +++

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0384`.

What does let promise?

The message points at line 2, the first assignment, and line 3, the one it refuses. The +++ under the help marks the one word the repair adds.

In PHP, $attempts = 1 can change anywhere later, and the line doesn't say whether you meant that. Rust asks you to say so. let attempts = 1; makes a binding: a name tied to a value. A let binding is immutable by default. It can't be reassigned or changed in place, so attempts += 1 is error E0384. mut makes a binding changeable. Take a look at Example 2, the working program for the rest of the lesson.

Example 2. Variables, types and mutability (examples/src/bin/b02_variables.rs)

// Lesson b02: variables, types and mutability.
const MAX_RETRIES: u32 = 3;

fn main() {
    // Immutable by default.
    let title = "Run tests";
    println!("title = {title}");

    // `mut` opts in to reassignment.
    let mut attempts = 0;
    attempts += 1;
    attempts += 1;
    println!("attempts = {attempts} of {MAX_RETRIES}");

    // The common scalar types.
    let price: f64 = 19.99;
    let in_stock: bool = true;
    let initial: char = 'R';
    let age_days: u32 = 42;
    println!("price = {price}, in_stock = {in_stock}, initial = {initial}, age_days = {age_days}");

    // Shadowing: a new binding with the same name, which may have a new type.
    let count = "3";
    let count: u32 = count.parse().expect("count should be a number");
    println!("count + 1 = {}", count + 1);

    // Conversions between number types are written out.
    let small: u8 = 200;
    let wide: u32 = small as u32 * 2;
    println!("wide = {wide}");

    // A tuple groups values of different types.
    let pair: (&str, u32) = ("retries", 3);
    println!("{} = {}", pair.0, pair.1);

    // Strings: &str is a view of text, String owns its text.
    let borrowed: &str = "Clear cache";
    let owned: String = borrowed.to_string();
    println!("{borrowed} / {}", owned.to_uppercase());
}

Run it with cargo run --quiet --bin b02_variables:

OUTPUT
title = Run tests
attempts = 2 of 3
price = 19.99, in_stock = true, initial = R, age_days = 42
count + 1 = 4
wide = 400
retries = 3
Clear cache / CLEAR CACHE

Start with attempts. It's declared with let mut attempts = 0;, two increments follow, and the program prints attempts = 2 of 3. Does mut change the value's type? No. It only allows reassignment.

Read each type by its name

PHP has one int and one float. Rust has families, and the name gives the size. In Example 2, price: f64 is a 64-bit float, in_stock: bool is a Boolean, and age_days: u32 is an unsigned 32-bit integer: u for unsigned, i for signed, digits for bits. initial: char holds one character, which gets its own section next.

Leave the annotation off, as title and attempts do, and the compiler infers the type. If nothing decides it, an integer literal becomes i32 and a decimal literal becomes f64.

How many bytes is 'é'?

The binding letter, on line 2 of examples/src/bin/b02_char_bytes.rs, held the position that it was one letter. It had a type annotation, char, and a value in single quotes, 'é', and nothing else on the line. It waited above a println! that was about to ask two questions about its size, the way a parcel waits on a kitchen scale. The program asked both. It printed 4 bytes in memory, and 2 bytes as UTF-8.

In PHP a string is a series of bytes, which is why strlen('café') is 5 and mb_strlen('café') is 4: bytes, then characters. Rust keeps the two counts apart, and gives a single character a type of its own. A char is one Unicode scalar value, written in single quotes, and always four bytes. Example 3 is an excerpt from that file.

Example 3. A char and a &str, lines 2 to 6 (excerpt) (examples/src/bin/b02_char_bytes.rs)

    let letter: char = 'é';
    println!("char {letter}: {} bytes in memory, {} bytes as UTF-8", std::mem::size_of::<char>(), letter.len_utf8());

    let word: &str = "café";
    println!("\"{word}\": {} chars, {} bytes", word.chars().count(), word.len());

Run the whole file with cargo run --quiet --bin b02_char_bytes. These are the first two lines it prints; it goes on to print two more, about a topic this track leaves out.

OUTPUT
char é: 4 bytes in memory, 2 bytes as UTF-8
"café": 4 chars, 5 bytes

'é' takes 4 bytes as a char, but its .len_utf8() is 2: the bytes it needs inside a UTF-8 string. For "café", .chars().count() gives 4 and .len() gives 5. len() counts bytes, as strlen does. The PHP version, php/b02_bytes.php, prints "café": 4 chars, 5 bytes, the same line.

Is 'é' the same as "é"? No. 'é' is a char, four bytes in memory. "é" is text, two bytes of UTF-8.¹

Why won't Rust turn "3" into 3?

Pass "3" to a PHP parameter typed int, and PHP turns it into 3, unless the file says declare(strict_types=1). Rust never makes that conversion for you. Take a look at Example 4, which asks it to.

Example 4. Text where a number belongs (examples/compile-fail/f02_types.rs)

fn main() {
    let retries: u32 = "3";
    println!("{retries}");
}

Compile it the same way as Example 1:

OUTPUT
error[E0308]: mismatched types
 --> compile-fail/f02_types.rs:2:24
  |
2 |     let retries: u32 = "3";
  |                  ---   ^^^ expected `u32`, found `&str`
  |                  |
  |                  expected due to this

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0308`.

That's error E0308, mismatched types: u32 expected on the left, &str found on the right.

Example 2 converts on purpose, with count.parse(). Parsing can fail, so .expect("count should be a number") does one of two things: it takes the number out, or it stops the program with that message. Lesson 7 keeps the failure as a value instead.

Numbers convert with as. small as u32 widens a u8, losing nothing, which is how 200 becomes wide = 400. Narrowing goes the other way, and it can cut bits off.

Shadowing is not mutation

Example 2 writes let count = "3";, and on the next line let count: u32 = ... with the same name. The second let makes a new binding that hides the first. That's shadowing. The first count holds text. The second holds a number. mut changes one binding, and its type stays put. Shadowing makes a new binding, so the type can change.

Shadowing will also let you reuse a name for any value you've just cleaned up, and it is, depending on how far apart the two lets sit and whether a reader will spot the second one and whether the old value still matters to anything below it, either a tidy way to say "same thing, now parsed" or a way to lose track of which count you're reading, and the compiler accepts both.

Two smaller things live in the same file. const MAX_RETRIES: u32 = 3; declares a constant, and a constant always states its type. pair is a tuple; pair.0 and pair.1 are its fields, printed as retries = 3.

&str and String

Two text types appear in signatures. borrowed is a &str, a string slice: a view of text stored elsewhere. owned is a String: text the program owns and can grow. borrowed.to_string() makes an owned copy, and the last output line, Clear cache / CLEAR CACHE, prints the slice and then an uppercased copy of the owned text. For now, read the type in the signature before you pick a conversion.

So every binding in Example 2 either says mut or doesn't, and the compiler holds you to it. Now ask the question of your own PHP. Which of your $variables actually change after their first line? Could you tell without reading the whole function?

Testing

Predict before you check: can adding mut make let retries: u32 = "3"; valid? No. mut allows reassignment. The value still has the wrong type, and parse() is the fix.

Then, without looking back, write one line that gives E0384 and one that gives E0308, and say which word fixes each. You can lean on the compiler for this. Its messages name the line and, often, the repair.

TL;DR

A let binding is immutable by default, and reassigning it is E0384; mut allows reassignment and leaves the type alone. Number types carry their size in the name, and unconstrained literals default to i32 and f64. A char is one Unicode scalar value, four bytes in memory; .len() on text counts bytes, like strlen. Rust never turns "3" into a number for you (E0308); parse() converts on purpose. Shadowing makes a new binding that may change type. A &str is a view of text; a String owns its text. Next: functions, and the semicolon that changes what they return.

¹ The é in the file is the single code point U+00E9. An editor that rewrites it as e followed by a combining accent changes the counts the program prints.

The sources.

Programs, their output and the compiler's messages were recorded on rustc 1.100.0 on 2026-11-30. Book locators are to The Rust Programming Language (3rd edition), Programming Rust (3rd edition) and Learn Rust in a Month of Lunches.

SOURCES — 7
  • Rust Book ch. 3.1 "Variables and Mutability", ch. 3.2 "Data Types", ch. 8.2 "Strings" [S20]
  • TRPL 3rd ed. ch. 3, Variables and Mutability 13.6 (immutability, E0384, shadowing, constants), Data Types 13.7 (f64 default, char as a Unicode scalar value); ch. 2, Comparing the Guess to the Secret Number (i32 default, E0308); ch. 8, Strings > Creating a New String 18.7 (to_string) [S17]
  • Programming Rust 3rd ed. ch. 3, Numeric Types > Integer Types (narrowing as truncates), Characters and Strings in Memory (len counts bytes); ch. 6, Blocks > Declarations (shadowing) [S18]
  • Learn Rust in a Month of Lunches 1.3 (len counts bytes) and 2.2 (to_string) [S19]
  • Rust standard library char and str [S24]
  • Rust Reference "Type cast expressions" [S25]
  • PHP Manual "Strings", strlen, mb_strlen, "Type juggling", "Type declarations" (strict typing) [S27].

Rust Book: Variables and Mutability · Rust Book: Data Types · Rust Book: Strings · Rust Reference: type cast expressions · Rust std: char · Rust std: str · Rust std: u32 · PHP Manual: Strings · PHP Manual: strlen · PHP Manual: mb_strlen · PHP Manual: Type juggling · PHP Manual: strict typing

NOT CHECKED — 4
  • Example 3 is part of a longer program. The whole program was run; the excerpt on its own was not.
  • That a narrowing as cast can cut bits off rests on Programming Rust; no program in this lesson shows it.
  • The PHP comparisons were run on PHP 8.5.8.
  • Book locators were checked against The Rust Programming Language, Programming Rust and Learn Rust in a Month of Lunches on 29 November 2026 and not re-read for this page.