Skip to content
Tutorials Center
My learning

Topics

Lesson 127 of 132 ยท Practice and Review

Reading Compiler Errors

Learn to read rustc errors and fix the common ones: E0382, E0499, E0502, E0505, E0308, E0277, E0599, E0106, E0425, E0597, E0004 and E0373, with real output.

Rust has a reputation for strict compiler errors, and it deserves it: the compiler refuses to build programs that could crash, leak or race. But it is also famous for the quality of those errors. A typical message points at the exact characters that are wrong, explains why in plain words and very often shows the fix. Beginners who learn to read the message instead of fighting it get productive much faster.

This lesson first explains how an error message is laid out, then walks through the twelve errors you will meet most often. Every one of them runs in the editor and fails on purpose with the real rustc 1.99 output (trimmed only when it is long), followed by the fix. Keep this page next to the cheat sheet and the lessons on ownership, borrowing and lifetimes, because most of these messages are the borrow checker doing its job.

Anatomy of an error message

Take the most famous one:

Rust E0382 use after move (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The output starts with error[E0382]: borrow of moved value: name``. Read it in layers:

  1. The headline error[E0382]: borrow of moved value: name``. The code in brackets is a stable identifier. You can search it, or run rustc --explain E0382 (in a real terminal) for a long explanation with examples.
  2. The arrow --> main.rs:4:16 is file:line:column of the main problem. Editors turn it into a link.
  3. The annotated source. Carets (^^^^) mark the primary spot, dashes (----) mark related spots, and each has a label. Here: name was declared with a type that "does not implement the Copy trait", the value was "moved here" on line 3, and was "borrowed here after move" on line 4. The three labels tell the whole story.
  4. help: and note: blocks usually propose a concrete change. Here: "consider cloning the value", showing name.clone() with the ++++++++ marking the added text.

The last two lines (aborting due to 1 previous error, the --explain hint) are boilerplate. When several errors appear, fix the first one first: later errors are often consequences of it, and a single fix may make five disappear.

Read the labels in source order, not the headline alone. Borrow-checker errors tell a small story ("borrowed here, mutated here, used here later"), and the fix is almost always to break one link of that story.

The fix for E0382 depends on what you meant. If both names really need the text, clone it. If other only needs to look at it, borrow it:

Rust E0382 fixed two ways

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The borrow checker family

E0499: two mutable borrows

Rust E0499 two mutable borrows (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The message is error[E0499]: cannot borrow v as mutable more than once at a time, with the labels "first mutable borrow occurs here", "second mutable borrow occurs here" and "first borrow later used here". The last label is the key: the first borrow a is still needed on line 5, so it is still alive when b is created. Two writers at once could invalidate each other (imagine a pushing while b reads a freed buffer after reallocation).

Fix: finish using one before creating the other, or simply use one reference.

Rust
fn main() {
    let mut v = vec![1, 2, 3];
    let a = &mut v;
    a.push(4);
    let b = &mut v; // fine: a is never used again
    b.push(5);
    println!("{v:?}");
}

This compiles because of non-lexical lifetimes: a borrow ends at its last use, not at the end of the block.

E0502: reading while writing

Rust E0502 shared and mutable borrow (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The message: error[E0502]: cannot borrow v as mutable because it is also borrowed as immutable. The labels point at &v[0] ("immutable borrow occurs here"), v.push(4) ("mutable borrow occurs here") and the println! ("immutable borrow later used here"). This is the classic bug that Rust prevents: push may reallocate the vector, which would leave first dangling. In C++ this is undefined behaviour; in Rust it does not compile.

Fix: use the value before mutating, or copy it out.

Rust E0502 fixed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

E0505: moving while borrowed

Rust E0505 move out while borrowed (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

error[E0505]: cannot move out of s because it is borrowed. Moving s into drop would free the text while r still points to it. Fix: let the borrow end first by printing before drop(s), or do not move at all.

E0597: does not live long enough

Rust E0597 dangling reference (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

error[E0597]: x does not live long enough. The labels explain it exactly: "binding x declared here", "x dropped here while still borrowed", "borrow later used here". The inner block ends, x dies, and r would point at nothing. Fix: declare the owner in the outer scope.

Rust
fn main() {
    let x = 5;
    let r = &x;
    println!("{r}");
}

E0507: moving out of an index

Rust E0507 cannot move out of a Vec (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

error[E0507]: cannot move out of index of Vec``. A vector owns its elements, so you cannot take one out and leave a hole. The help text offers both fixes: borrow with &names[0], or clone with names[0].clone(). To really take ownership of an element use names.remove(0) or names.swap_remove(0), or consume the vector with into_iter().

Type and trait errors

E0308: mismatched types

Rust E0308 wrong type (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The output is error[E0308]: mismatched types with expected i32, found &str``. The compiler never converts types behind your back. Parse the text instead: let count: i32 = "3".parse().unwrap(); (see Reading Input and Numeric Conversion).

The same code appears in a sneakier form, a stray semicolon:

Rust E0308 the stray semicolon (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The message says expected i32, found ()``, the label "implicitly returns () as its body has no tail or return expression" and, on the semicolon, "help: remove this semicolon to return this value". Remove it and the function returns 8.

E0277: a trait is not implemented

Rust E0277 missing Display (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

error[E0277]: Pointdoesn't implementstd::fmt::Display``. The note adds: "in format strings you may be able to use {:?} (or {:#?} for pretty-print) instead". That is the quick fix (add #[derive(Debug)] and print {p:?}); the proper fix for user-facing text is to implement Display, as shown in Display and From.

E0277 is the compiler's way of saying "this type does not have the capability this code needs". You will also see it as cannot add f64toi32``: Rust does not mix integer and float arithmetic implicitly. Convert on purpose, 5_i32 as f64 + 2.5, or better f64::from(5_i32) + 2.5. The long list of "other types implement trait Add" below the message is noise; read the first lines.

Rust E0277 fixed with Debug and Display

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

E0599: no such method

Rust E0599 unknown method (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

error[E0599]: no method named incrementfound for structCounter in the current scope. Three common causes: a typo, a missing impl block (add impl Counter { fn increment(&mut self) { self.n += 1; } }), or a trait method whose trait is not in scope or not implemented. For the last case the compiler often adds "items from traits can only be used if the trait is implemented and in scope". Generic code gets a variant: "the method exists but its trait bounds were not satisfied", which means you need T: Clone (or similar) in the signature.

Lifetimes and scope

E0106: missing lifetime specifier

Rust E0106 which borrow does the result keep? (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

error[E0106]: missing lifetime specifier with the label "expected named lifetime parameter" and the explanation: "this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from a or b". The help even prints the corrected signature: fn longest<'a>(a: &'a str, b: &'a str) -> &'a str. Apply it and the program prints ab. If the function can only ever return one of the inputs, give only that input the lifetime. If it creates new text, return an owned String instead. The full story is in Lifetimes.

E0425: unresolved name

Rust E0425 a typo (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

error[E0425]: cannot find value totl in this scope, followed by "a local variable with a similar name exists" and the corrected line. A missing import produces the sibling pair E0425/E0433 ("use of undeclared type HashMap") and a help line use std::collections::HashMap; that you can paste at the top of the file.

E0384 and E0596: forgot mut

Rust E0384 assigning twice (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

error[E0384]: cannot assign twice to immutable variable score``, and the help is "consider making this binding mutable" with let mut score. (rustc also prints a warning that the first value is never read; fixing the error removes it.) Its sibling is E0596, cannot borrow list as mutable, as it is not declared as mutable, raised when you call list.push(1) on a binding without mut. Same cure. Immutable by default is a feature: when you see mut, you know that value changes.

Patterns and threads

E0004: non-exhaustive match

Rust E0004 a missing case (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

error[E0004]: non-exhaustive patterns: Light::Yellow not covered. The compiler names the missing variant and even draws it as not covered under the enum definition. Add an arm for Light::Yellow, or _ => if you really want a catch-all. Prefer listing the variants: when you add a new one later, the compiler will point at every match that must be updated, which is a huge help in large programs.

E0373: a closure may outlive its function

Rust E0373 thread borrows a local (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

error[E0373]: closure may outlive the current function, but it borrows name, which is owned by the current function. A spawned thread can run longer than main's locals, so it must own what it uses. The help is precise: "use the move keyword", shown as move ||. Fix and run:

Rust E0373 fixed with move

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Note that name now belongs to the thread, so main can no longer use it. If you need it back, clone before the closure, or use thread::scope (see Threads).

A routine for any error

  1. Read the first error only. Scroll up; the top of the output is the cause.
  2. Read the labels in order and tell the story in your own words.
  3. Try the help: suggestion, but ask whether it matches your intent. clone() silences many borrow errors, and sometimes that is right, but sometimes the real fix is a better design (pass &T, return an owned value, split a struct).
  4. Look up the code with rustc --explain E0xxx or search for it.
  5. Rebuild often. Fix one thing, compile, repeat. In a real project, cargo check is much faster than a full build.
  6. Warnings are information. unused variable, unused Result (a must-use warning) and dead-code messages often point at real bugs. See Clippy and rustfmt.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In error[E0382]: borrow of moved value, what does the code E0382 let you do?

    Error codes are stable identifiers. rustc --explain E0382 prints a long description with examples, and you can search for the code. The line and column come from the arrow line instead.
  2. 2. Which situation produces E0502?

    E0502 is a shared (&) borrow overlapping a mutable use, such as holding &v[0] while calling v.push(). Two mutable borrows are E0499, use after move is E0382 and a missing lifetime is E0106.
  3. 3. What is the best fix for fn double(n: i32) -> i32 { n * 2; }?

    The semicolon turns the last expression into a statement, so the body evaluates to (). Removing it makes n * 2 the tail expression, and the function returns an i32.
  4. 4. Why does thread::spawn(|| println!("{name}")) give E0373?

    A spawned thread requires a 'static closure. Borrowing name ties the closure to main's stack frame, so the compiler asks for move to give the closure ownership.
  5. 5. When several errors are printed, which should you fix first?

    One mistake, such as a wrong type or a missing import, often causes a cascade of follow-up errors. Fix the first, recompile and see what remains.

Summary

  • An error message has a headline with a code, an arrow with file, line and column, labelled source snippets and help: or note: lines.
  • Read the labels in order; borrow errors tell a short story about where a value was moved or borrowed and where it was used later.
  • E0382 is use after move, E0499 and E0502 are conflicting borrows, E0505 is a move while borrowed, E0597 is a reference that outlives its owner.
  • E0308 is a type mismatch (watch for a stray semicolon), E0277 is a missing trait such as Display, E0599 is a missing method.
  • E0106 asks you to say which input a returned reference borrows from; E0004 lists the match case you forgot; E0373 wants move for threads.
  • Fix the first error first, recompile often, and treat clone() as a choice rather than a reflex.

Next: Practice Problems: Fundamentals