Visibility and mutability of struct's fields

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?

1 Like

I don't know if someone has already written a macro like:

pub struct Foo {
    #[ref_getter]
    baz: SomeType,
}
1 Like

Someone has indeed: getset

2 Likes

You can make an item public but annotate it with #[doc(hidden)], which instructs rustdoc to skip the item entirely. By convention, undocumented items are not considered part of the public API, and there's precedent in libstd for using #[doc(hidden)] (in io::ErrorKind for example).