Rust 2021 and unsafe functions

I recently started doing a bit of experimenting with unsafe rust, and I ended up encountering the warning unused_unsafe where I didn't expect it. Here is a simplified example.

The following function

unsafe fn testing() {
    let i = 3;
    let mut j = 1;
    unsafe { copy(&i, &mut j, 1) };

raises the following warning:

warning: unnecessary `unsafe` block
 --> src/
3 | unsafe fn testing() {
  | ------------------- because it's nested under this `unsafe` fn
6 |     unsafe { copy(&i, &mut j, 1) };
  |     ^^^^^^ unnecessary `unsafe` block
  = note: `#[warn(unused_unsafe)]` on by default

warning: 1 warning emitted

I know that unsafe fn means that the entire body of the unsafe function is a unsafe block. However, I remember reading somewhere a discussion about this choice, and that it would be better to change it, and require developers to explicitly put the relevant parts of the body in unsafe blocks. I even thought that this change was planned, and that the above warning was not shown, and that there was already a warning in place (either in rustc or clippy) to warn developers that they should use redundant unsafe blocks in that case to have more granularity over where unsafe operations can be used.

It seems I remember wrong, but I haven't been able to find where I read about this. So, with the recent release of the Plan for the Rust 2021 Edition, I wonder why this change isn't a part of the 2021 edition.

The lint is named unsafe_op_in_unsafe_fn, and it was stabilized in Rust 1.52.0 (releases notes). Currently it is allow-by-default, but it may become warn-by-default or even a hard error in the future.


According to RFC 2585, the plan is for the unsafe_op_in_unsafe_fn lint to become warn-by-default in all editions, and possibly deny-by-default in some future edition. Enabling this lint is also supposed to disable the unused_unsafe lint within unsafe functions, though it looks like this hasn't been implemented yet. So eventually your code above should be warning-free in all editions, if this RFC is implemented as written.


Thanks for your answer!

The tracking issue shows that there is some debate indeed.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.