Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is `pub(self)` visibility different from no `pub` attribute?

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?

like image 310
palotasb Avatar asked Jun 18 '18 08:06

palotasb


People also ask

What does pub crate mean in Rust?

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) .

What is pub 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.

What is pub mod?

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.

How do you make a public function in Rust?

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.


1 Answers

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 just item.

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 in self as the $arg to get the effect of a non-pub definition.

like image 132
Lukas Kalbertodt Avatar answered Oct 19 '22 04:10

Lukas Kalbertodt