对应 panic 时的栈展开或终止
当出现 panic 时,程序默认会开始 展开(unwinding),这意味着 Rust 会回溯栈并清理它遇到的每一个函数的数据,不过这个回溯并清理的过程有很多工作。另一种选择是直接 终止(abort),这会不清理数据就退出程序。那么程序所使用的内存需要由操作系统来清理。如果你需要项目的最终二进制文件越小越好,panic 时通过在 Cargo.toml[profile] 部分增加 panic = 'abort',可以由展开切换为终止。例如,如果你想要在release模式中 panic 时直接终止:

  1. [profile.release]
  2. panic = 'abort'

使用 panic! 的 backtrace

  1. $ RUST_BACKTRACE=1 cargo run
  2. thread 'main' panicked at 'index out of bounds: the len is 3 but the index is 99', src/main.rs:4:5
  3. stack backtrace:
  4. 0: rust_begin_unwind
  5. at /rustc/7eac88abb2e57e752f3302f02be5f3ce3d7adfb4/library/std/src/panicking.rs:483
  6. 1: core::panicking::panic_fmt
  7. at /rustc/7eac88abb2e57e752f3302f02be5f3ce3d7adfb4/library/core/src/panicking.rs:85
  8. 2: core::panicking::panic_bounds_check
  9. at /rustc/7eac88abb2e57e752f3302f02be5f3ce3d7adfb4/library/core/src/panicking.rs:62
  10. 3: <usize as core::slice::index::SliceIndex<[T]>>::index
  11. at /rustc/7eac88abb2e57e752f3302f02be5f3ce3d7adfb4/library/core/src/slice/index.rs:255
  12. 4: core::slice::index::<impl core::ops::index::Index<I> for [T]>::index
  13. at /rustc/7eac88abb2e57e752f3302f02be5f3ce3d7adfb4/library/core/src/slice/index.rs:15
  14. 5: <alloc::vec::Vec<T> as core::ops::index::Index<I>>::index
  15. at /rustc/7eac88abb2e57e752f3302f02be5f3ce3d7adfb4/library/alloc/src/vec.rs:1982
  16. 6: panic::main
  17. at ./src/main.rs:4
  18. 7: core::ops::function::FnOnce::call_once
  19. at /rustc/7eac88abb2e57e752f3302f02be5f3ce3d7adfb4/library/core/src/ops/function.rs:227
  20. note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.