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?
1 Answer
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.