The Safety and Robustness of Rust

This topic has been translated from a Chinese forum by GPT and might contain errors.

Original topic: Rust的安全性和稳健型

| username: 非凸科技

Rust is designed around safety and robustness. That is, safe code is code that does not use the unsafe keyword, and sound code is code that does not cause memory corruption or other undefined behavior. “Undefined behavior” (UB) has a specific meaning in languages like C, C++, and Rust, different from “unspecified” or “implementation-defined” behavior.

One of Rust’s most important features is the commitment that all safe code is reliable. However, this commitment can be broken when unsafe code is involved, and unsafe code is almost always involved somewhere.

Data structures like Vec and HashMap have unsafe code in their implementations, just like any function that interacts with the operating system, such as File::open. This leads to a common question: “If Rust cannot guarantee that all safe code is reliable, how can it be a memory-safe language?”

Rust has a list of behaviors considered undefined. Sound functions maintain the following invariants: any program that only calls sound functions and does not contain any other unsafe code cannot commit UB.

Functions that do not directly or indirectly use unsafe code are guaranteed to be reliable. A function that does not directly use any unsafe code but calls other sound functions is also sound by definition. However, functions and modules that directly use unsafe code may not be sound, and callers of unsound functions may also be unsound. Any unsoundness in the safety or public API of a module is a bug.

Reference: Safety and Soundness in Rust

| username: Billmay表妹 | Original post link

Thank you for your sharing~