A stack trace, called a backtrace in Rust, records the function calls leading to a program point or failure. When a test panics, it can show the path from Rust’s runtime code back to your own function and source line. Read the entries from the bottom upward to find where your code triggered the problem. section 14.2.2
Use a backtrace when the ordinary panic or test output does not reveal the cause:
- Enable RUST_BACKTRACE=1 for a shorter trace, or RUST_BACKTRACE=full for a more detailed one. section 14.2.2
- Capture one during execution with std::backtrace::Backtrace::capture(). section 21.3
- Check BacktraceStatus to distinguish Disabled, Captured, and Unsupported before displaying it. section 21.3
- Remember that RUST_LIB_BACKTRACE or RUST_BACKTRACE values other than 0 enable capture for the runtime API. section 21.3
Finding the failing line
If a failing assertion reports `playground::two_is_two` at `src/lib.rs:3:5`, that entry points to the test code that triggered the panic. The surrounding runtime entries are usually less useful for locating your bug. section 14.2.2
use std::{
backtrace::{Backtrace, BacktraceStatus::*},
panic,
};
fn main() {
panic::set_hook(Box::new(|_| {
println!("Panicked! Trying to get a backtrace...");
let backtrace = Backtrace::capture(); #1
match backtrace.status() { #2
Disabled => println!("Backtrace isn't enabled, sorry"),
Captured => println!("Here's the backtrace!!\n{backtrace}"),
Unsupported => println!("No backtrace possible, sorry"), #3
// Do some database shutting down stuff
}
}));
std::env::set_var("RUST_BACKTRACE", "0"); #4
panic!();
}
This example combines a panic hook, runtime capture, environment-based enablement, and status handling. section 21.3






