A Rust error appears, and the quickest move is to paste it into a chat window and apply whatever comes back. Sometimes that works, but it skips the best explanation on offer. The compiler wrote the error about your code, at the exact lines involved, and it often contains a fix, the reason for it, and sometimes a note: with a better fix than its own help:.

In the order of authority this site uses, the compiler comes second, after the code itself and well ahead of AI output. Every error below is pasted from a real cargo check run (with the Rust version shown above). The wording can change between compiler versions, so yours may differ slightly.

The parts of an error

fn longest_line(lines: Vec<String>) -> usize {
    lines.iter().map(String::len).max().unwrap_or(0)
}

fn main() {
    let lines = vec![String::from("compile"), String::from("read the error")];
    let width = longest_line(lines);
    println!("{} lines, the longest is {width} bytes", lines.len());
}
error[E0382]: borrow of moved value: `lines`
 --> src/main.rs:8:56
  |
6 |     let lines = vec![String::from("compile"), String::from("read the error")];
  |         ----- move occurs because `lines` has type `Vec<String>`, which does not implement the `Copy` trait
7 |     let width = longest_line(lines);
  |                              ----- value moved here
8 |     println!("{} lines, the longest is {width} bytes", lines.len());
  |                                                        ^^^^^ value borrowed here after move
  |
note: consider changing this parameter type in function `longest_line` to borrow instead if owning the value isn't necessary
 --> src/main.rs:1:24
  |
1 | fn longest_line(lines: Vec<String>) -> usize {
  |    ------------        ^^^^^^^^^^^ this parameter takes ownership of the value
  |    |
  |    in this function
help: consider cloning the value if the performance cost is acceptable
  |
7 |     let width = longest_line(lines.clone());
  |                                   ++++++++

For more information about this error, try `rustc --explain E0382`.
error: could not compile `longest-line` (bin "longest-line") due to 1 previous error

Every part has a job:

  • Header: the level (error or warning), an error code, and a summary. A move hands ownership of a value to someone else, after which the old name is unusable; a borrow is temporary access through a reference (&) while the owner keeps the value.
  • Location: --> gives the file, line and column.
  • Primary label: the ^^^^^ marks where the compiler found the problem.
  • Secondary labels: the ----- lines are context. Read them in line order and they tell a story: lines is created on line 6 as a Vec<String>, which is not Copy (a trait, a named capability a type can have; Copy types, such as integers, are duplicated automatically on assignment); it moves into longest_line on line 7; it is used again on line 8.
  • note: extra information, here with a location of its own. It points at the parameter and asks whether the function needs to own the value at all.
  • help: a suggested edit, as a diff. The ++++++++ sits under the characters it would insert.
  • Footer: where to read more, then Cargo’s summary.

Here is a one-line summary of the same error, written by hand for illustration: “lines was moved into longest_line, so add .clone().” It is accurate, and it has dropped the note:, the one line that asks a design question.

Two suggestions, one design question

Here the help: and the note: point in different directions, and the note is right: longest_line only reads its lines, so it should borrow them, not own them. The rustc development guide says that help is for “changes the user can possibly make to fix the problem” and note for “other context, information and facts”. In the JSON output (cargo check --message-format=json), the .clone() suggestion is marked MachineApplicable, which the guide defines as “can be applied mechanically”: a tool may apply it without asking. That is a statement about the edit, not about your design. Applied, the call becomes:

let width = longest_line(lines.clone());

It compiles and prints 2 lines, the longest is 14 bytes, by copying the vector and every string in it so that a function can read them once.

The note’s fix is to change the signature so that the function borrows:

pub fn longest_line(lines: &[String]) -> usize {
    lines.iter().map(String::len).max().unwrap_or(0)
}

let width = longest_line(&lines);

&[String] is a slice: a borrowed view of a run of Strings. The caller lends its vector with &lines, Rust converts the &Vec<String> to a slice automatically, and nothing is copied.

Is the clone ever right? It depends on what the function does with its argument. If it stored the vector or sent it to another thread, it would need to own it, and a clone at the call site might be the honest answer; When is a clone the right answer? works through those cases. A function that only reads should borrow, as in the first pattern in Reviewing AI-written Rust. Clippy agrees, if you ask: needless_pass_by_value, in the off-by-default pedantic group, flags the cloning version.

rustc --explain

Most errors have a code, and the compiler carries a longer explanation of each:

$ rustc --explain E0382
A variable was used after its contents have been moved elsewhere.

Erroneous code example:

It continues with an example program and the ways out: lend a reference, make a copy with .clone(), mark a small type Copy, or share ownership with Rc. Borrowing comes first. The same text is in the online error codes index. The explanation is general; the diagnostic is about your code. Between them they often answer the question you were about to type.

A borrow-checker error, label by label

The borrow checker is the part of the compiler that checks references against Rust’s rules. The central rule: while a shared, read-only borrow (&) is in use, nothing may take an exclusive, mutable one (&mut); while an exclusive one is in use, nothing else may borrow the value at all.

fn main() {
    let mut queue = vec![String::from("build"), String::from("test")];
    let next = &queue[0];
    queue.push(String::from("deploy"));
    println!("next up: {next}");
}
error[E0502]: cannot borrow `queue` as mutable because it is also borrowed as immutable
 --> src/main.rs:4:5
  |
3 |     let next = &queue[0];
  |                 ----- immutable borrow occurs here
4 |     queue.push(String::from("deploy"));
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
5 |     println!("next up: {next}");
  |                         ---- immutable borrow later used here

For more information about this error, try `rustc --explain E0502`.
error: could not compile `queue` (bin "queue") due to 1 previous error

Line 3 borrows from queue, read-only. Line 4, the primary label, needs exclusive access, because push changes the vector. Line 5 is the label a summary tends to drop, and it explains the error: the read-only borrow is still in use there. A borrow lasts until its last use, not until the end of the block.

The rule matters here because a vector keeps its elements side by side, and a push may move them all to a bigger allocation. In the Rust book’s words, “the reference to the first element would be pointing to deallocated memory.”

There is no help: this time; the labels are the explanation. The fix depends on what next is for. If you need it only before the push, finish with it first:

let next = &queue[0];
println!("next up: {next}");
queue.push(String::from("deploy"));

If it must survive the push, take an owned copy of that one element:

let next = queue[0].clone();
queue.push(String::from("deploy"));
println!("next up: {next}");

One short string, one small allocation: fine. Cloning the whole queue on every pass of a busy loop would be another matter.

When the suggestion is wrong for your design

A lifetime is the compiler’s name for how long a borrow is valid. &str is a borrowed view of some text; String is text you own.

fn first_word(text: String) -> &str {
    text.split_whitespace().next().unwrap_or("")
}

fn main() {
    println!("{}", first_word(String::from("read the error")));
}
error[E0106]: missing lifetime specifier
 --> src/main.rs:1:32
  |
1 | fn first_word(text: String) -> &str {
  |                                ^ expected named lifetime parameter
  |
  = help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from
help: consider using the `'static` lifetime, but this is uncommon unless you're returning a borrowed value from a `const` or a `static`
  |
1 | fn first_word(text: String) -> &'static str {
  |                                 +++++++
help: instead, you are more likely to want to change the argument to be borrowed...
  |
1 | fn first_word(text: &String) -> &str {
  |                     +
help: ...or alternatively, you might want to return an owned value
  |
1 - fn first_word(text: String) -> &str {
1 + fn first_word(text: String) -> String {
  |

For more information about this error, try `rustc --explain E0106`.
error: could not compile `first-word` (bin "first-word") due to 1 previous error

Two more pieces of anatomy: a line starting with = has no code of its own to point at, and a diff with - and + lines replaces a whole line.

The = help: line is the diagnosis. A returned &str must borrow from something that outlives the call, and the only input is a String that the function owns and drops when it returns. When there is exactly one reference among the inputs, Rust assumes that the result borrows from it and no lifetime needs writing; here there is none.

The compiler ranks its three suggestions itself: 'static, the lifetime of a borrow valid for the whole program, is “uncommon”; borrowing the argument is “more likely”. In the JSON output all three are MaybeIncorrect, which the guide explains as “the suggestion may or may not be a good one”. Applied as written:

  • &'static str gives a new error, E0515: “cannot return value referencing function parameter text”. The annotation makes a promise the function cannot keep.
  • text: &String gives E0308 at the call site, “expected &String, found String”, with a help to add & there. With that, it compiles, and Clippy’s default ptr_arg lint warns that “writing &String instead of &str involves a new object where a slice will do”.
  • -> String gives E0308 in the body, “expected String, found &str”, with a help to add .to_string().

Each is a direction, not a finished patch. Together, the second help and Clippy point at a different signature:

pub fn first_word(text: &str) -> &str {
    text.split_whitespace().next().unwrap_or("")
}

let text = String::from("read the error");
let word = first_word(&text);

The caller lends its String with &text, which Rust converts to &str. The result is a slice of the caller’s text: nothing is copied, and no annotation is needed. Return a String only if the result must outlive the text; that costs an allocation, and sometimes it is worth it. Adding 'static because the compiler mentioned it is one of the risky signs the course page lists: “lifetime annotations added before simpler ownership changes have been tried”.

A routine for errors

  1. Run cargo check. It skips the final code generation step, which the Cargo book notes makes it faster than cargo build. Some diagnostics only appear during code generation, so build and test before you finish.
  2. Read the whole diagnostic: header, labels in line order, then each note: and help:.
  3. Question each help:. Ask what it changes about the design, not only whether it compiles. A clone or a lifetime is a decision about ownership.
  4. Change one thing, check, read again. Then you know which edit fixed the error, or caused the next one.
  5. Still stuck? Ask. Try rustc --explain, then an assistant, giving it the whole diagnostic and the code, not the headline. Check the answer against the error. Does it deal with the primary label? Does it compile? Does it fix the error or move it, as 'static did? Is it the help: line in other words?

Module 0 of Rust Primer, Field setup, builds the habit of changing one thing, compiling, testing and explaining.