Allow safety checks inside unsafe functions

Currently, if I write an Rust function that needs some conditions to be checked by the coder, it makes sense to mark the function unsafe. This has the undesirable effect of disabling safety checks for the entirety of the function when there might just be a single statement that introduces the unsafety.

I propose that safety checks be enabled for unsafe functions if they contain at least one unsafe {} block. This would help catch accidental usage of unsafe operations.

If that isn't practical, then as odd as it sounds maybe we need a safe {} block, but then there would be the complexity of needing to be able to put arbitrary levels of unsafe blocks inside safe blocks and vice versa.

This can be worked around by having a "safe" internal function, that actually isn't safe and exporting it as an unsafe function. IMO this introduces extra risk of misunderstanding were someone may come along later and mistake the "safe" version as actually safe.

This is RFC 2585, and you can currently opt-in to the lint #[warn(unsafe_op_in_unsafe_fn)].



Nice! I tried to find when the lint became available by looking in the release notes but didn't find it, then discovered it already works on beta so that it will be stabilized in 1.52.0.

1 Like

Ah, I actually didn't realize that the stabilized lint hasn't been released yet. I just found that was in PR79208, which is indeed marked for relnotes in the 1.52.0 milestone.