19

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 ?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
ustulation
  • 3,600
  • 25
  • 50
  • 4
    Not possible yet. Wait for [RFC 1422](https://github.com/rust-lang/rfcs/pull/1422) to solve this issue. – oli_obk Feb 02 '16 at 09:19
  • 1
    The RFC 1422 was [accept](https://github.com/rust-lang/rfcs/pull/1422#issuecomment-199443868) on 21 Mar 2016. – malbarbo May 06 '16 at 15:07

2 Answers2

25

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
Isaac Woods
  • 1,114
  • 1
  • 17
  • 28
1

As a workaround, it's possible to make something public, and then hide in from documentation with #[doc(hidden)]. Hidden bits are supposed to be not a part of the API, etc. and generally people won't use them anyway since they rely on docs and examples.

dpc.pw
  • 3,462
  • 1
  • 19
  • 24