While working with Rust over the last few months, I've been trying to understand the best practices around visibility of fields in structs. My inclination is to default to making fields private and use getters/setters to interact with them; however, that leads to two issues (that I've run into):
- You can't deconstruct a type using pattern matching; which is very nice syntactic sugar to have available.
- When using getters/setters, the borrow rules checker becomes lower resolution and will mark the entire struct as being borrowed even if you are only borrowing a single field. For example, in
let x = s.get_z()
andlet x = &s.z
the former would considers
to be borrowed for the rest of the life ofx
while the latter would only considers.z
to be borrowed for the life ofx
.
Those two items create some pressure for me to make fields public for some level (usually pub(super)
); but I'm not sure if this is "smell" that points to issues in my designs that I am missing or if this is considered perfectly fine in Rust (and my concerns are just carry over from OOP). So are there best practices or guidelines around visibility in Rust?