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:
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:
Run tests / Clear cacheOne 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:
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 emittedrustc --edition=2024 -D warnings compile-warn/w09_unused_variable.rs stops:
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 errorA 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:
after unset($first)
freed: Run tests
after unset($second)
tasks: 1, copy: 2Unset $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:
owner holds: Run tests
dropped: Run tests
after the blocklet 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);
}
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.