When I define a struct, I often want (some) of its fields to be publicly visible, but I don't want them to be pub
because I don't want to make them free to change from the outside. So I end up writing a lot of functions to expose this fields to the outside. For example:
pub struct Foo {
bar: Bar,
}
impl Foo {
pub fn get_bar(&self) -> &Bar {
&self.bar
}
}
I see this pattern happening all the time and I wonder if there's a simpler way to immutably expose a struct
's field.
Moreover, each of Bar
's methods that require &mut self
need to be exposed through Foo
's interface. For example:
pub struct Bar {
num: u32,
}
impl Bar {
pub fn add_one(&mut self) {
self.num += 1;
}
}
will require
impl Foo {
pub fn add_one(&mut self) {
self.bar.add_one();
}
}
Is all of this really necessary?