对应 panic 时的栈展开或终止
当出现 panic 时,程序默认会开始 展开(unwinding),这意味着 Rust 会回溯栈并清理它遇到的每一个函数的数据,不过这个回溯并清理的过程有很多工作。另一种选择是直接 终止(abort),这会不清理数据就退出程序。那么程序所使用的内存需要由操作系统来清理。如果你需要项目的最终二进制文件越小越好,panic 时通过在 Cargo.toml 的 [profile] 部分增加 panic = 'abort',可以由展开切换为终止。例如,如果你想要在release模式中 panic 时直接终止:
[profile.release]panic = 'abort'
使用 panic! 的 backtrace
$ RUST_BACKTRACE=1 cargo runthread 'main' panicked at 'index out of bounds: the len is 3 but the index is 99', src/main.rs:4:5stack backtrace:0: rust_begin_unwindat /rustc/7eac88abb2e57e752f3302f02be5f3ce3d7adfb4/library/std/src/panicking.rs:4831: core::panicking::panic_fmtat /rustc/7eac88abb2e57e752f3302f02be5f3ce3d7adfb4/library/core/src/panicking.rs:852: core::panicking::panic_bounds_checkat /rustc/7eac88abb2e57e752f3302f02be5f3ce3d7adfb4/library/core/src/panicking.rs:623: <usize as core::slice::index::SliceIndex<[T]>>::indexat /rustc/7eac88abb2e57e752f3302f02be5f3ce3d7adfb4/library/core/src/slice/index.rs:2554: core::slice::index::<impl core::ops::index::Index<I> for [T]>::indexat /rustc/7eac88abb2e57e752f3302f02be5f3ce3d7adfb4/library/core/src/slice/index.rs:155: <alloc::vec::Vec<T> as core::ops::index::Index<I>>::indexat /rustc/7eac88abb2e57e752f3302f02be5f3ce3d7adfb4/library/alloc/src/vec.rs:19826: panic::mainat ./src/main.rs:47: core::ops::function::FnOnce::call_onceat /rustc/7eac88abb2e57e752f3302f02be5f3ce3d7adfb4/library/core/src/ops/function.rs:227note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.
