Skip to content

Commit

Permalink
Improve note on unsafe functions and unsafe blocks (#4204)
Browse files Browse the repository at this point in the history
Improve note on unsafe functions and `unsafe` blocks

See discussion in #4147, #4148.

---------

Co-authored-by: Matthias Totschnig <[email protected]>
  • Loading branch information
chriskrycho and Matthias Totschnig authored Jan 21, 2025
1 parent 8a0eee2 commit 486408f
Showing 1 changed file with 6 additions and 8 deletions.
14 changes: 6 additions & 8 deletions src/ch20-01-unsafe-rust.md
Original file line number Diff line number Diff line change
Expand Up @@ -186,14 +186,11 @@ With the `unsafe` block, we’re asserting to Rust that we’ve read the functio
documentation, we understand how to use it properly, and we’ve verified that
we’re fulfilling the contract of the function.

> Note: In earlier versions of Rust, the body of an unsafe function was treated
> as an `unsafe` block, so you could perform any unsafe operation within the
> body of an `unsafe` function. In later versions of Rust, the compiler will
> warn you that you need to use an `unsafe` block to perform unsafe operations
> in the body of an unsafe function. This is because Rust now distinguishes
> between `unsafe fn`, which defines what you need to do to call the function
> safely, and an `unsafe` block, where you actually uphold that “contract” the
> function establishes.
To perform unsafe operations in the body of an unsafe function, you still need
to use an `unsafe` block just as within a regular function, and the compiler
will warn you if you forget. This helps to keep `unsafe` blocks as small as
possible, as unsafe operations may not be needed across the whole function
body.

#### Creating a Safe Abstraction over Unsafe Code

Expand Down Expand Up @@ -550,5 +547,6 @@ Rust’s official guide to the subject, the [Rustonomicon][nomicon].
[the-slice-type]: ch04-03-slices.html#the-slice-type
[reference]: ../reference/items/unions.html
[miri]: https://github.com/rust-lang/miri
[editions]: appendix-05-editions.html
[nightly]: appendix-07-nightly-rust.html
[nomicon]: https://doc.rust-lang.org/nomicon/

0 comments on commit 486408f

Please sign in to comment.