I have sometimes wanted to have read-only fields in Rust, so I was glad to learn about the accepted restrictions RFC. It isn't my favorite syntax for the feature[1], but they all have different flaws. However, one line in the alternatives section of the RFC book entry was confusing to me:
some positions such as
enum
variants do not semantically accept a visibility, while they do accept a restriction
This didn't make much sense to me, since a mut
restriction does not seem useful on enum
variants, or at least much less useful than a visibility. Additionally, the future possibilities section of the same entry suggests as a future possibility:
mut
could be placed on thestruct
or variant itself, which would be equivalent to having the same restriction on each field
While I can understand that adding visibilities to enum
variants might be much more difficult than adding mut
restrictions (because of pub
currently being implicit on all enum
variants), enum
variant members getting visibility seems much more useful than getting mut
restrictions, and there's no semantic reason why enum
variant members couldn't accept a visibility, as far as I can tell, other than that they don't currently.
So, what does the RFC mean when it talks about mut
restrictions being used in places where visibilities are not semantically allowed?
My favorite syntax is similar to the syntax described in this issue comment, with two changes: I'd want
ref in …
to indicate where a field can be referenced (rather than that being indicated just by the path), and that I think that the commas should either be replaced with semicolons or usein *
for everywhere (this becomes helpful because ofpub(ref, mut in crate
being confusing). To give a specific example of one benefit mentioned in the comment ("It's more scalable") which I don't think has been pointed out elsewhere, I think that this syntax would be a good fit forunsafe
fields, like so:
↩︎struct Example { pub( unsafe mut in *, ref in crate, mut in self, // ideally `in mod` would work too ) scary_pointer: *mut (), }