I see that functions' visibility can be declared to be pub(self)
within a module. How is this different from a private function with no pub
attribute? Why does this syntax exist if they are not different?
pub(in path) makes an item visible within the provided path . path must be a parent module of the item whose visibility is being declared. pub(crate) makes an item visible within the current crate. pub(super) makes an item visible to the parent module. This equivalent to pub(in super) .
pub(super) makes an item visible to the parent module. This is equivalent to pub(in super) . pub(self) makes an item visible to the current module. This is equivalent to pub(in self) or not using pub at all.
The mod keyword is used to declare submodules. We need to explicitly declare functions, structs etc as public so they can be consumed in other modules. The pub keyword makes things public. The use keyword is used to shorten the module path. We don't need to explicitly declare 3rd party modules.
Modules in Rust are private by default. On the contrary, functions in a public module can be accessed by other modules. Modules should be prefixed with pub keyword to make it public.
The pub(restricted)
syntax was introduced in RFC 1422. It introduces two new ways to specify visibility:
pub(crate)
: makes the item visible to the whole current crate, but not beyond.pub(in path::to::module)
: makes the item visible to the module tree specified by the path.pub(self)
is syntactic sugar for pub(in self)
, which falls into the second category: self
is just a path like super
, ::foo
, bar::baz
and so on. This means that, yes, pub(self)
makes the item visible to the current module tree.
Thus, pub(self)
is equivalent to omitting the pub(self)
declaration. This is even stated in the RFC:
As noted above, the definition means that
pub(self) item
is the same as if one had written justitem
.
The RFC also mentions why this is supported:
The main reason to support this level of generality (which is otherwise just "redundant syntax") is macros: one can write a macro that expands to
pub($arg)
item, and a macro client can pass inself
as the$arg
to get the effect of a non-pub definition.
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