运行时保障

Rust 没有运行时未定义行为:

  • 数组访问有边界检查。
  • Integer overflow is defined (panic or wrap-around).

关键点:

  • Integer overflow is defined via the overflow-checks compile-time flag. If enabled, the program will panic (a controlled crash of the program), otherwise you get wrap-around semantics. By default, you get panics in debug mode (cargo build) and wrap-around in release mode (cargo build --release).

  • 边界检查不能使用编译标志禁用,也不能直接通过 unsafe 关键字禁用。然而, unsafe 允许你调用 slice::get_unchecked 等不做边界检查的函数。