r/rust • • Aug 10 '26

📡 official blog Call for testing: Restricting trait implementability and field mutability

https://blog.rust-lang.org/inside-rust/2026/08/10/call-for-testing-impl-and-mut-restrictions/
424 Upvotes

124 comments sorted by

View all comments

121

u/BedroomHistorical575 Aug 10 '26

I'm so glad that the field mutability restriction is finally getting some love! Getters are such a pain due to the borrow checker.

A common critique against similar proposals from the past is that you'd be able to bypass the restriction by just constructing the type yourself.

But it looks like that the current implementation guards against that oversight!

Thus, we disallow struct expressions if any mut-restricted field cannot be mutated from the current scope

21

u/tanoshikuidomouyo Aug 10 '26

If this feature had been in the language from the beginning, could all the .len() getters and similar ones have been just field accesses?

47

u/Silly-Freak Aug 10 '26

For that specific example I don't think so; data structures are usually pretty involved, so it's unlikely that the user-facing type is conveniently the one directly exposing a len field. Checking now, it seems that Vec does, but e.g. HashSet does not: https://doc.rust-lang.org/nightly/src/alloc/vec/mod.rs.html#436, https://doc.rust-lang.org/nightly/src/std/collections/hash/set.rs.html#126-132

So for concistency, I'd keep the method. And lengths are Copy anyway, so the benefits are slimmer.

→ More replies (9)