MARY.WIN

RUSTY — BEGINNER — B09

Reading compiler errors: the bridge to
ownership

Read a Rust diagnostic in four stops, make the most common first repair, and compare who frees a value in PHP and in Rust.
Lesson 9 of 9 in Rust beginner track. Before you start: Lessons 2 to 8.

You give a struct a field of type String. You set it to "Run tests". You compile, and nothing runs. The compiler prints a diagnostic instead.

In PHP with strict types on, passing 42 where a string is declared gives a TypeError when that line runs. Rust checks before there is a program, and the message it prints can look like a wall. You don't have to read it all at once.

This lesson covers reading a compiler message in the order it is written, using its error code, repairing the most common first error, &str where String is expected, and telling a warning from an error. Then it asks the question the main series opens with: when your program is done with a value, who frees it? It assumes Lessons 2 to 8, and it revisits errors from Lessons 2 and 5. Ownership gets one definition here; the main series takes it from there, starting at E0382, where this lesson ends.

Take a look at Example 1.

Example 1. Complete example (examples/compile-fail/f09_string_vs_str.rs)

struct Task {
    title: String,
}

fn main() {
    let task = Task { title: "Run tests" };
    println!("{}", task.title);
}

Compile it from the examples folder:

TERMINAL
rustc --edition=2024 compile-fail/f09_string_vs_str.rs
error[E0308]: mismatched types
 --> compile-fail/f09_string_vs_str.rs:6:30
  |
6 |     let task = Task { title: "Run tests" };
  |                              ^^^^^^^^^^^ expected `String`, found `&str`
  |
help: try using a conversion method
  |
6 |     let task = Task { title: "Run tests".to_string() };
  |                                         ++++++++++++

error: aborting due to 1 previous error

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

For comparison, the PHP file php/b09_types.php turns on strict_types, declares a string constructor parameter, and passes 42. Its recorded run printed TypeError at run time: Task::__construct(): Argument #1 ($title) must be of type string, int given, from inside the running script.

How do you read a diagnostic?

Read it in four stops, top to bottom.

Stop one is the headline: error[E0308]: mismatched types. E0308 is an error code, and rustc --explain E0308 prints a longer explanation that starts: "Expected type did not match the received type."¹

Stop two is the location, 6:30: line 6, column 30.

Stop three is the label under the carets: expected String, found &str. The field wants text it owns. "Run tests" is a string slice, a view of text stored somewhere else. You met both types in Lesson 2.

Stop four is the help: try using a conversion method, .to_string(). The compiler prints line 6 again with the change in place and marks the added characters with +.

Should you always do what the help says? Not always. It makes this line compile. Whether the field should own its text is your call, and the help's .to_string() is, depending on whether Task is meant to keep its own title or only to look at text that lives somewhere else, and on whether that text will one day come from a form instead of a literal in the source, either the repair the program needs or a way to quiet the message without answering its question. Here the Task keeps its own title. It is the repair.

The repair

Example 2 makes it twice, two different ways.

Example 2. Two owned titles (examples/src/bin/b09_string_fixed.rs)

// Lesson b09: the repair for the most common first error, &str where String is expected.
struct Task {
    title: String,
}

fn main() {
    let task = Task { title: "Run tests".to_string() };
    let also = Task { title: String::from("Clear cache") };
    println!("{} / {}", task.title, also.title);
}

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

OUTPUT
Run tests / Clear cache

One Task gets "Run tests".to_string(), and the other gets String::from("Clear cache"). Both create an owned String. Then run cargo check again. Several errors can share one cause, so fix the first one and check again.

Would adding mut fix this E0308? No. mut lets a binding change; it doesn't turn &str into String. It fixes E0384 from Lesson 2, assigning twice to an immutable variable, and E0596 from Lesson 5, borrowing as mutable something that isn't declared mut.

Errors and warnings

The binding draft held a String that read Write notes, and nothing in main ever asked for it. main was two lines long. The second was a println! of the words built anyway. The compiler read both lines, printed a warning that named draft, suggested _draft if this was intentional, and built the program. Given -D warnings, the same compiler read the same two lines and built nothing.

Here is the file, and the two messages.

Example 3. An unused variable (examples/compile-warn/w09_unused_variable.rs)

fn main() {
    let draft = String::from("Write notes");
    println!("built anyway");
}

rustc --edition=2024 compile-warn/w09_unused_variable.rs prints a warning and builds:

OUTPUT
warning: unused variable: `draft`
 --> compile-warn/w09_unused_variable.rs:2:9
  |
2 |     let draft = String::from("Write notes");
  |         ^^^^^ help: if this is intentional, prefix it with an underscore: `_draft`
  |
  = note: `#[warn(unused_variables)]` (part of `#[warn(unused)]`) on by default

warning: 1 warning emitted

rustc --edition=2024 -D warnings compile-warn/w09_unused_variable.rs stops:

OUTPUT
error: unused variable: `draft`
 --> compile-warn/w09_unused_variable.rs:2:9
  |
2 |     let draft = String::from("Write notes");
  |         ^^^^^ help: if this is intentional, prefix it with an underscore: `_draft`
  |
  = note: `-D unused-variables` implied by `-D warnings`
  = help: to override `-D warnings` add `#[allow(unused_variables)]`

error: aborting due to 1 previous error

A warning flags something suspicious, and the program still builds. An error means there is no program. The source line is the same in both messages; only the lint level changed.

The build failed, and the last line is a warning. Did the warning stop it? Look for error first. By default, a warning alone doesn't stop the build. If one did, look for deny in the lint settings.

Who frees a value?

Now the question the main series opens with. When your program is done with a value, who frees it?

In PHP, the engine counts. A variable lives in a container the PHP Manual calls a zval, with a refcount: how many names point at it. After $second = $first, the count is two. At zero, the container is freed.² Take a look at Example 4.

Example 4. Two names, one object (php/b09_memory.php)

<?php
declare(strict_types=1);

final class Task
{
    public function __construct(public string $title) {}

    public function __destruct()
    {
        echo "freed: {$this->title}", PHP_EOL;
    }
}

$first = new Task('Run tests');
$second = $first;
unset($first);
echo "after unset(\$first)", PHP_EOL;
unset($second);
echo "after unset(\$second)", PHP_EOL;

$tasks = ['Run tests'];
$copy = $tasks;
$copy[] = 'Clear cache';
echo "tasks: ", count($tasks), ", copy: ", count($copy), PHP_EOL;

Run it with php php/b09_memory.php:

OUTPUT
after unset($first)
freed: Run tests
after unset($second)
tasks: 1, copy: 2

Unset $first, and nothing is freed. Unset $second, and the destructor prints freed: Run tests. Arrays are different: assignment copies the value, so adding to $copy leaves $tasks with one item. Two values that point at each other never reach zero, so since PHP 5.3 a cycle collector finds them. All of this happens while the script runs.

The Rust answer

Rust decides before the program runs, with rules called ownership. Ownership is Rust's way of managing memory without a garbage collector. Each value has one owner at a time, and when the owner goes out of scope, the value is dropped. The compiler checks the rules, and they don't slow the running program. Take a look at Example 5, which hands a value from one name to another inside a block.

Example 5. A move and a drop (examples/src/bin/b09_drop.rs)

struct Task {
    title: String,
}

impl Drop for Task {
    fn drop(&mut self) {
        println!("dropped: {}", self.title);
    }
}

fn main() {
    {
        let task = Task { title: String::from("Run tests") };
        let owner = task;
        println!("owner holds: {}", owner.title);
    }
    println!("after the block");
}

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

OUTPUT
owner holds: Run tests
dropped: Run tests
after the block

let owner = task; hands the Task to a new name. That is a move: the new place owns it. impl Drop for Task is code Rust runs when a Task is freed; traits come in tutorial 8 of the main series. dropped: Run tests prints at the inner block's closing brace, before after the block.

After the move, can you still print task.title, the way $first kept working in PHP? Example 6 tries.

Example 6. Using the old name (examples/compile-fail/f09_use_after_move.rs)

struct Task {
    title: String,
}

fn main() {
    let task = Task { title: String::from("Run tests") };
    let owner = task;
    println!("{}", owner.title);
    println!("{}", task.title);
}
OUTPUT
error[E0382]: borrow of moved value: `task`
 --> compile-fail/f09_use_after_move.rs:9:20
  |
6 |     let task = Task { title: String::from("Run tests") };
  |         ---- move occurs because `task` has type `Task`, which does not implement the `Copy` trait
7 |     let owner = task;
  |                 ---- value moved here
8 |     println!("{}", owner.title);
9 |     println!("{}", task.title);
  |                    ^^^^^^^^^^ value borrowed here after move
  |
note: if `Task` implemented `Clone`, you could clone the value
 --> compile-fail/f09_use_after_move.rs:1:1
  |
1 | struct Task {
  | ^^^^^^^^^^^ consider implementing `Clone` for this type
...
7 |     let owner = task;
  |                 ---- you could clone this value

error: aborting due to 1 previous error

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

No. E0382: borrow of moved value task. A move ends the old name's access.

Which name should own it?

So the repair compiles, the warning builds, and the Drop line prints at the closing brace. The lesson could stop there. But put the two answers side by side. In Example 4, unset($first) freed nothing, because $second still pointed at the same object, and PHP kept it for as long as any name did. In Example 6, the old name lost its access the moment the value moved. Which objects in your own PHP code have two names right now? Did anyone mean both of them to keep the object alive? If each had to have one owner, which would it be?

Testing

Take the last compiler error you hit and read it in four stops: code, location, label, help. You don't have to understand every note. You can fix the first error and check again.

Then cover the outputs of Examples 4 and 5, predict the order of the lines, and run both. For each of Examples 1, 3 and 6, say before compiling whether you'll get an error or a warning, and for an error, which code.

TL;DR

A Rust diagnostic reads in four stops: the headline with its error code, the location, the label, and the help, and rustc --explain expands the code. The most common first error, &str where String is expected, is repaired with .to_string() or String::from; mut doesn't repair it. A warning lets the build finish unless warnings are denied, and an error doesn't. PHP frees an object when its reference count reaches zero, while the script runs. Rust decides before the program runs: each value has one owner, a move hands it on, and the value is dropped when its owner goes out of scope. The main series starts from E0382.

¹ The Rust compiler error index publishes an explanation for each code, one page per code. The ones this lesson uses are linked under References.

² The example shows the behaviour, not the count itself. The counts in this paragraph come from the PHP Manual's chapter on garbage collection.

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 — 1
  • Rust Book [S20] ch. 4.1 "What Is Ownership?", 8.2 "Storing UTF-8 Encoded Text with Strings"; std docs [S24] std::ops::Drop; Error Codes Index [S63] E0308, E0382, E0384, E0596; rustc book [S64] "What is rustc?", "Lint Levels"; rustc --explain; PHP Manual [S27] "Type declarations", "Arrays", "Constructors and Destructors"; PHP Manual [S66] "Reference Counting Basics", "Collecting Cycles". Books: TRPL 3rd ed. [S17] ch. 8 "Strings > Creating a New String" 18.7, ch. 4 "What Is Ownership? > Moving Data"; Programming Rust 3rd ed. [S18] ch. 8 "Attributes"; Learn Rust in a Month of Lunches [S19] 2.2.

Error index: E0308 · Error index: E0384 · Error index: E0596 · Error index: E0382 · Rust Book: What is ownership? · Rust Book: Strings · std: Drop · rustc book: What is rustc? · rustc book: Lint levels · PHP Manual: Type declarations · PHP Manual: Arrays · PHP Manual: Constructors and destructors · PHP Manual: Reference counting basics · PHP Manual: Collecting cycles

NOT CHECKED — 7
  • The warning example was compiled, with and without -D warnings, but its program was never run. The words built anyway are read from its source, not from recorded output.
  • That an ordinary warning does not stop a build is documented in the rustc book; none of the three Rust books checked states it.
  • rustc --explain is not covered in the three Rust books checked; the quoted first line comes from running it on rustc 1.100.0.
  • The reference counts in the PHP section come from the PHP Manual's garbage-collection chapter. The example shows the behaviour, not the counts, and the cycle collector is described, not demonstrated.
  • PHP's behaviour without strict_types was not run; the lesson's example turns it on.
  • That ownership's checks do not slow the running program is the Rust Book's statement; nothing in this lesson measures it.
  • Compiler messages were recorded with rustc 1.100.0, and PHP output with PHP 8.5.8. Another version can word or lay out the same error differently.