Hide self-referential structs behind a friendly wrapper
mainThe #[self_referencing] macro adds many public methods to a struct (like borrow_{field} and with_mut). To avoid exposing this cluttered API to users of your library, it is recommended to use an internal/external pattern:
- Define an
Internalstruct annotated with#[self_referencing]. - Define a
Friendlypublic struct that contains theInternalstruct as a private field. - Implement your desired public API on the
Friendlystruct, wrapping the complexity of the internal self-referential logic.
#[self_referencing]
struct Internal {
// ...
}
// This struct provides a clean interface for library users
pub struct Friendly {
internal: Internal,
}
impl Friendly {
pub fn new() -> Self {
// Implementation details...
Friendly { internal: InternalBuilder { ... }.build() }
}
pub fn do_the_thing(&self) -> T {
// Use self.internal.borrow_...() here
}
}