Answer#
A panic is the program stopping itself because a rule was broken that Rust cannot continue from. The message has a fixed shape.
fn main() {
let items: Vec<i32> = Vec::new();
let first = items.first().unwrap();
println!("{first}");
}thread 'main' (39588) panicked at src/main.rs:3:31:
called `Option::unwrap()` on a `None` value
note: run with `RUST_BACKTRACE=1` environment variable to display a backtracethread 'main': which thread panicked (the number in brackets differs on every run).src/main.rs:3:31: file, line and column. Go there first.called Option::unwrap() on a None value: the reason. Herefirst()returnedNonebecause the list is empty.- The note at the end: the program can show more, see below.
How to get a backtrace#
Set the environment variable RUST_BACKTRACE=1 before running (in PowerShell: $env:RUST_BACKTRACE = "1"; in a POSIX shell: RUST_BACKTRACE=1 ./program). The stack of calls is printed after the message. This output was shortened to its first frames.
thread 'main' (8844) panicked at src/main.rs:3:31:
called `Option::unwrap()` on a `None` value
stack backtrace:
0: std::panicking::panic_handler
1: core::panicking::panic_fmt
2: core::panicking::panic
3: core::option::unwrap_failed
4: main::main
...Read from the top. The first frames are inside the standard library (std::panicking, core::...); the first frame with your own function name (main::main here) is the code that caused it. A debug build shows the file and line for each frame; the lines were left out above for length.
How to fix it#
Handle the case instead of assuming it cannot happen:
fn main() {
let items: Vec<i32> = Vec::new();
match items.first() {
Some(first) => println!("{first}"),
None => println!("the list is empty"),
}
}the list is emptyCommon panic messages#
called Option::unwrap() on a None valueorcalled Result::unwrap() on an Err value: ...: unwrapping something that was empty or failed. Usematch,if let,?orunwrap_or.index out of bounds: the len is 3 but the index is 10: use.get(i).attempt to add with overflow(debug builds): see the thread on debug and release builds.already borrowedfromRefCell, or a poisonedMutex: a rule about shared access was broken at run time.
Common mistakes#
- Ignoring the line number and searching by the message alone.
- Catching panics to continue as if nothing happened. A panic usually means a bug; fix the cause or return a
Result.