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()and
let x = &s.zthe former would consider
sto be borrowed for the rest of the life of
xwhile the latter would only consider
s.zto be borrowed for the life of
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?