Search code examples
rustencapsulation

C++ Friend-like construct for Rust


In certain cases I would like to leverage whatever alternative there is in Rust to C++'s friend keyword. In crate A I have the following modules:

mod a0:

pub struct A {
    pub a0: u8,
    a1: SomeType,
}

impl A {
    pub fn fa0(...) { ... }
    fn fa1(...) { ... }
}

Modules b0 and c0 need access to all public and private members of A. Code cannot do that unless it is in mod a0. I want to expose only A, A::a0 and A::fa0 to other crates interfacing with this crate, but within this crate I want access to the complete implementation of A (public and private).

I usually end up doing something like:

mod a0:

pub struct A {
    pub a0: u8,
    inner: Inner
}

pub struct Inner { /* all pub fields */ }

pub fn get_inner<'a>(obj: &'a mut A) -> &'a Inner {
     &mut obj.inner
}

Modules b0 and c0 access get_inner and hence Inner, while in lib.rs I do:

mod a0;
mod b0;
mod c0;

pub use a0::A; // so other crates cannot use get_inner(...) etc.

This seems very convoluted and I seem to be missing something. Or is this the only way to do it ?


Solution

  • Now RFC 1422 has been accepted, this is possible! You can replace pub in structure definitions with:

    • pub(crate) to allow access within the current crate
    • pub(super) to allow access to the current module's parent as well
    • pub(in some_module) to allow access from some_module