Sub topic 14
Building a minimal reproduction
This chapter assumes you can read a rustc diagnostic (error code, message, labeled spans, notes, help) and run cargo check. It also assumes you know the common error families: moves, borrows, lifetimes, and trait bounds. A minimal reproduction is the smallest complete program that still produces the error you are stuck on. Building one is a debugging technique, and it is also the thing you attach when you ask someone else for help.
Why a reproduction helps
A real project has hundreds of lines, several modules, and dependencies. The compiler's error is caused by a handful of those lines. Everything else is noise, for you and for anyone you ask.
Shrinking the program has three benefits:
- It forces you to find which lines the error depends on. Often you understand the cause before you finish shrinking.
- Cascading errors disappear, because you removed the code that produced them.
- A helper can paste your code into the Rust Playground, run it, and see exactly what you see.
The goal is not the shortest possible program. The goal is the smallest program that fails with the same error code for the same reason.
The reduction loop
Work in a scratch location so you never damage your real code. Either copy the failing code into a new project or use the Rust Playground.
cargo new repro
cd repro
cargo checkThen repeat this loop:
- Copy the failing function and the types it uses into
src/main.rs. - Run
cargo checkand confirm you see the same error code. - Remove or simplify one thing.
- Run
cargo checkagain. - If the error code is unchanged, keep the removal. If the error changed or vanished, undo the removal. That code mattered.
Change one thing at a time. If you delete five things at once and the error disappears, you do not know which deletion mattered.
What to remove or simplify
Try these reductions, roughly in this order:
- Delete code that runs after the error line. Later code is rarely the cause.
- Delete unrelated functions, modules, and
uselines. - Replace large types with small ones. A
HashMap<String, u32>often becomes aVec<u32>. A struct with ten fields often needs two. - Replace real values with literals such as
1orString::new(). - Remove generics, lifetimes, and trait impls that are not named in the error.
- Remove external crates. If the error persists without them, they were not involved.
Keep these things, because the error usually depends on them:
- The exact shape of the borrow: whether it is
&,&mut, or a move. - Whether the code is inside a method taking
&selfor&mut self. - The relative order of the statements the labels point to.
A worked example
Suppose this inventory code is part of a larger project. cargo check reports an error in restock.
use std::collections::HashMap;
struct Inventory {
items: HashMap<String, u32>,
log: Vec<String>,
}
impl Inventory {
fn record(&mut self, name: &str) {
self.log.push(format!("restocking {name}"));
}
fn restock(&mut self, name: &str, amount: u32) {
let count = self.items.entry(name.to_string()).or_insert(0);
self.record(name);
*count += amount;
}
}
fn main() {
let mut inv = Inventory {
items: HashMap::new(),
log: Vec::new(),
};
inv.restock("bolts", 10);
println!("{:?} {:?}", inv.items, inv.log);
}The compiler reports E0499, cannot borrow *self as mutable more than once at a time. The labels point at self.items.entry(...) as the first mutable borrow and at self.record(name) as the second. They also point at *count += amount as the later use of the first borrow.
Step 1: remove code that is not in the labels
main is not mentioned in the labels. Replace its body with nothing, since cargo check only needs the program to be well formed. Replace the println! and construction code with an empty main. The error remains, so keep that change.
Step 2: simplify the types
The labels talk about *self, not about HashMap. Replace the map with a Vec<u32>. Remove name and amount. Again the error remains.
struct Inventory {
items: Vec<u32>,
log: Vec<String>,
}
impl Inventory {
fn record(&mut self) {
self.log.push(String::new());
}
fn restock(&mut self) {
let first = &mut self.items[0];
self.record();
*first += 1;
}
}
fn main() {}Running cargo check on this still gives E0499 with the same three labels. This is the minimal reproduction. It is 15 lines and has no imports. The shape is now visible: a mutable borrow of a field is alive while a &mut self method is called.
Step 3: try one more reduction and watch it fail
You could reduce further to this:
fn main() {
let mut v = vec![1];
let a = &mut v;
let b = &mut v;
a.push(1);
b.push(2);
}This produces E0499 too, but it is no longer your problem. It loses the method call on self, which is the part that makes the error confusing in your real code. A reduction that keeps the code error but drops the cause is over-reduced. Go back one step.
Step 4: use the reproduction to fix the real code
The reduction shows that self.record() needs the whole of *self, while first still holds a borrow of part of it. Two fixes work. You can call record before taking the borrow, or you can finish using the borrow before calling record. Applying the first to the original code:
use std::collections::HashMap;
struct Inventory {
items: HashMap<String, u32>,
log: Vec<String>,
}
impl Inventory {
fn record(&mut self, name: &str) {
self.log.push(format!("restocking {name}"));
}
fn restock(&mut self, name: &str, amount: u32) {
self.record(name);
let count = self.items.entry(name.to_string()).or_insert(0);
*count += amount;
}
}
fn main() {
let mut inv = Inventory {
items: HashMap::new(),
log: Vec::new(),
};
inv.restock("bolts", 10);
println!("{:?} {:?}", inv.items, inv.log);
}This compiles. The mutable borrow count now starts after record returns, so the two borrows never overlap.
Check that you reproduced the right error
A reproduction is only useful if it matches. Compare these against the original diagnostic:
| Check | Why it matters |
|---|---|
| Same error code | A different code means a different problem. |
| Same kind of labels | The labeled spans should point at the same kinds of code, such as a first borrow, a second borrow, and a later use. |
| Same notes and help | Differences in the `note:` or `help:` lines suggest you changed the type or trait involved. |
| Same Rust edition | Edition 2015, 2018, 2021, and 2024 differ in some rules. Use the edition from your `Cargo.toml`. |
If the error changed code during reduction, you have found something useful. You now have two errors. The first one was hiding the second, or your edit introduced a new one.
Common reduction mistakes
- Deleting the line the error points at. The error disappears because you removed the thing you are trying to understand. Simplify it instead.
- Making the reproduction depend on a missing item. If your scratch code gives E0425 or E0433 for a name you deleted, you have introduced an unrelated error. Fix those first, since cascading errors can hide the one you care about.
- Adding
#[allow(...)]orunsafeto silence things. This changes what the compiler checks. - Switching to a different toolchain channel. Use the same version when possible, and record it with
rustc --version. - Keeping warnings that are not related. Unused variable warnings are harmless but distracting. Prefix names with an underscore or add
#[allow(dead_code)]to keep the output clean.
What to include when asking for help
A good question has four parts:
- One sentence saying what you expected and what happened.
- The reproduction as a complete program that compiles except for the one error.
- The full diagnostic copied from the terminal, not a screenshot or a paraphrase.
- The output of
rustc --version, and your edition if it is not the 2021 default.
Paste the diagnostic exactly as printed by cargo check. The spans, notes, and help lines carry information that a summary drops.
Related tools
- The Rust Playground lets you share a reproduction as a link. Choose the same edition and channel as your project.
cargo checkis faster thancargo buildand gives the same diagnostics, so use it inside the loop.rustc --explain E0499describes the error code with a short example. Compare your reproduction to that example. If it looks like the example, you probably know the fix.
Exercises
Exercise
The following program fails with E0382. Reduce it to a minimal reproduction that still fails with E0382, then say which lines you removed and why. use std::collections::HashMap; struct Report { title: String, scores: HashMap<String, u32>, } fn printtitle(r: Report) { println!("{}", r.title); } fn main() { let mut scores = HashMap::new(); scores.insert("ana".tostring(), 3); let report = Report { title: "Q1".tostring(), scores }; printtitle(report); println!("{}", report.scores.len()); }
Show answer
A minimal reproduction is:
struct Report {
title: String,
}
fn consume(r: Report) {
let _ = r;
}
fn main() {
let report = Report { title: String::new() };
consume(report);
println!("{}", report.title);
}
The HashMap, the scores field, and the insert call are not needed, because the error is about report being moved into the function and then used. The String field is kept because it makes Report non-Copy, so the move happens. A struct of only u32 fields would not fail unless it were left without Copy, which would change the shape of the problem. The reduced program still reports E0382, borrow of moved value, with the move label on the call and the use label on the last line.
Exercise
You are shrinking a program with an E0502 error. After you delete a function, cargo check reports E0425 cannot find function instead. What happened, and what should you do?
Show answer
The function you deleted was called elsewhere, so you introduced a new, unrelated error and the compiler stopped before the borrow check could report E0502. Undo the deletion, or replace the function with a minimal stub that has the same signature, and run cargo check again to confirm E0502 returns. Only keep a reduction when the original error code still appears.