|
4 | 4 |
|
5 | 5 | ## Summary
|
6 | 6 |
|
| 7 | +- The [`unsafe_op_in_unsafe_fn`] lint now warns by default. |
| 8 | + This warning detects calls to unsafe operations in unsafe functions without an explicit unsafe block. |
| 9 | + |
| 10 | +[`unsafe_op_in_unsafe_fn`]: ../../rustc/lints/listing/allowed-by-default.html#unsafe-op-in-unsafe-fn |
| 11 | + |
7 | 12 | ## Details
|
8 | 13 |
|
| 14 | +The [`unsafe_op_in_unsafe_fn`] lint will fire if there are [unsafe operations] in an unsafe function without an explicit [`unsafe {}` block][unsafe-block]. |
| 15 | + |
| 16 | +```rust |
| 17 | +# #![warn(unsafe_op_in_unsafe_fn)] |
| 18 | +unsafe fn get_unchecked<T>(x: &[T], i: usize) -> &T { |
| 19 | + x.get_unchecked(i) // WARNING: requires unsafe block |
| 20 | +} |
| 21 | +``` |
| 22 | + |
| 23 | +The solution is to wrap any unsafe operations in an `unsafe` block: |
| 24 | + |
| 25 | +```rust |
| 26 | +# #![deny(unsafe_op_in_unsafe_fn)] |
| 27 | +unsafe fn get_unchecked<T>(x: &[T], i: usize) -> &T { |
| 28 | + unsafe { x.get_unchecked(i) } |
| 29 | +} |
| 30 | +``` |
| 31 | + |
| 32 | +This change is intended to help protect against accidental use of unsafe operations in an unsafe function. |
| 33 | +The `unsafe` function keyword was performing two roles. |
| 34 | +One was to declare that *calling* the function requires unsafe, and that the caller is responsible to uphold additional safety requirements. |
| 35 | +The other role was to allow the use of unsafe operations inside of the function. |
| 36 | +This second role was determined to be too risky without explicit `unsafe` blocks. |
| 37 | + |
| 38 | +More information and motivation may be found in [RFC #2585]. |
| 39 | + |
| 40 | +[unsafe operations]: ../../reference/unsafety.html |
| 41 | +[unsafe-block]: ../../reference/expressions/block-expr.html#unsafe-blocks |
| 42 | +[RFC #2585]: https://rust-lang.github.io/rfcs/2585-unsafe-block-in-unsafe-fn.html |
| 43 | + |
9 | 44 | ## Migration
|
| 45 | + |
| 46 | +The [`unsafe_op_in_unsafe_fn`] lint is part of the `rust-2024-compatibility` lint group. |
| 47 | +In order to migrate your code to be Rust 2024 Edition compatible, run: |
| 48 | + |
| 49 | +```sh |
| 50 | +cargo fix --edition |
| 51 | +``` |
| 52 | + |
| 53 | +Alternatively, you can manually enable the lint to find places where unsafe blocks need to be added, or switch it to `allow` to silence the lint completely. |
| 54 | + |
| 55 | +```rust |
| 56 | +// Add this to the root of your crate to do a manual migration. |
| 57 | +#![warn(unsafe_op_in_unsafe_fn)] |
| 58 | +``` |
0 commit comments