External Publication
Visit Post

Private unsafe fields are a poorly motivated feature

Rust Internals [Unofficial] February 6, 2026
Source

scottmcm:

I would not make that new_unchecked function an unsafe fn

I find this a very strange, counter-productive recommendation. I would never do that.

My reasons have nothing to do with memory safety.

The reason I'd never do that is that by exposing a safe new_unchecked I've just thrown out encapsulation, type-based correctness out of the window. As a user of the number theory crate, when I see a Prime, I want to know that no matter what I do (barring language or library UB, obviously), that is going to be a prime. Correct by construction. Make invalid states unrepresentable. I want there to be no way to create a Prime that is not a prime.

When a user of my crate shows me his binary that produces a Prime { p: 9 }, and I can see that his binary doesn't have any unsafe blocks, I want to instantly know: aha, obviously my crate has a bug.

By not marking new_unchecked unsafe, you've just gotten rid of this whole type-based correctness knowledge. To debug a Prime { p: 9 } I now have to study both the library crate and the user crate.

Discussion in the ATmosphere

Loading comments...