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 ?
Rust is syntactically similar to C++, but it provides increased speed and better memory safety. Rust is a more innovative system-level language in terms of safer memory management because it does not allow dangling pointers or null pointers.
Rust is far easier to learn than C++, but as the Recent Rust Developer Survey highlighted, very few people can currently code in Rust proficiently. Employers like B2C2, therefore, are flexible when it comes to hiring.
You can easily notice similarities between Rust and C++ syntax, but Rust offers a higher level of memory safety without using a garbage collector. Not for the first time, Rust has been named the most loved language—it gained more than 86% of developers' votes.
Rust doesn't have any special feature that makes it fast and different from C and/or C++. It is much safer than C++ because of protection mechanisms it follows which, in principle, are also doable in C++ (using std::unique_ptr and std::shared_ptr ).
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 cratepub(super)
to allow access to the current module's parent as wellpub(in some_module)
to allow access from some_module
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With