当前位置: 首页 > 文档资料 > 通过例子学 Rust >

标准库类型 - panic!

优质
小牛编辑
134浏览
2023-12-01

panic! 宏可用于产生一个 panic (恐慌),并开始展开它的栈。在展开栈的同时,运行时将会释放该线程所拥有的所有资源,是通过调用对象的析构函数完成。

因为我们正在处理的程序只有一个线程,panic! 将会引发程序上报 panic 消息并退出。

  1. // 再次实现整型的除法(/)
  2. fn division(dividend: i32, divisor: i32) -> i32 {
  3. if divisor == 0 {
  4. // 除以一个 0 时会引发一个 panic
  5. panic!("division by zero");
  6. } else {
  7. dividend / divisor
  8. }
  9. }
  10. // `main` 任务
  11. fn main() {
  12. // 堆分配的整数
  13. let _x = Box::new(0i32);
  14. // 此操作将会引发一个任务失败
  15. division(3, 0);
  16. println!("This point won't be reached!");
  17. // `_x` 在此处将被销毁
  18. }

由分析知道, panic!不会泄露内存

  1. $ rustc panic.rs && valgrind ./panic
  2. ==4401== Memcheck, a memory error detector
  3. ==4401== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
  4. ==4401== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info
  5. ==4401== Command: ./panic
  6. ==4401==
  7. thread '<main>' panicked at 'division by zero', panic.rs:5
  8. ==4401==
  9. ==4401== HEAP SUMMARY:
  10. ==4401== in use at exit: 0 bytes in 0 blocks
  11. ==4401== total heap usage: 18 allocs, 18 frees, 1,648 bytes allocated
  12. ==4401==
  13. ==4401== All heap blocks were freed -- no leaks are possible
  14. ==4401==
  15. ==4401== For counts of detected and suppressed errors, rerun with: -v
  16. ==4401== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)