Sub topic 4
Controlling visibility with pub
This chapter assumes you can write modules and refer to items by path, as covered in the previous two chapters. It also assumes you know basic structs, enums, and traits. Here you will learn the privacy rule the compiler applies, the four forms of pub, how privacy works for fields and variants, and the errors you will see when you get it wrong.
The default is private
Every item in Rust (function, struct, enum, constant, module, trait) is private by default. "Private" has a precise meaning: an item is visible inside the module where it is defined, and in all of that module's descendants. It is not visible to the module's parent or to siblings.
This gives you one rule to remember: code can see the private items of its own module and of every ancestor module. It cannot see private items in modules that sit below or beside it.
mod outer {
fn secret() -> u32 {
1
}
pub mod inner {
pub fn call() -> u32 {
super::secret() + 1
}
}
pub fn run() -> u32 {
inner::call()
}
}
fn main() {
println!("{}", outer::run());
}inner::call reads secret, which is private to outer. That is allowed because inner is a descendant of outer. The reverse does not work: outer could not call a private function defined inside inner.
Note that inner itself is marked pub. Visibility applies at every step of a path. To call outer::inner::call from the crate root, inner and call must both be visible there. outer is visible at the root because the root is its parent and it is defined in that module.
The four forms of pub
Plain pub makes an item visible wherever its parent module is visible. Three restricted forms narrow that reach.
| Form | Visible to |
|---|---|
| (nothing) | The current module and its descendants |
| `pub(self)` | Same as nothing; rarely written |
| `pub(super)` | The parent module and its descendants |
| `pub(crate)` | Everywhere inside the current crate, but not to other crates |
| `pub(in path)` | The named ancestor module and its descendants |
| `pub` | Anywhere the parent module is reachable, including other crates if the whole path is public |
The following program uses three of the restricted forms:
mod network {
pub mod server {
pub(super) fn handshake() -> &'static str {
"hello"
}
pub(crate) fn port() -> u16 {
8080
}
pub(in crate::network) fn internal_id() -> u32 {
7
}
pub fn start() -> String {
format!("{} on {}", handshake(), port())
}
}
pub fn connect() -> String {
format!("{} id={}", server::handshake(), server::internal_id())
}
}
fn main() {
println!("{}", network::connect());
println!("{}", network::server::start());
println!("{}", network::server::port());
// network::server::handshake(); // error[E0603]: function `handshake` is private
}handshake is pub(super), so it is visible in network but not in the crate root where main lives. port is pub(crate), so main can call it. The path in pub(in path) must name an ancestor of the item, and crate::network is an ancestor of server. In 2018 and later editions the path must start with crate, self, or super.
When to choose pub(crate)
In a library, pub(crate) is the most useful restricted form. It lets modules across your crate share helpers while keeping them out of the public API that downstream users depend on. Anything marked plain pub and reachable from outside becomes a commitment: changing it can break other people's code. Anything pub(crate) can be changed freely.
A reasonable habit is to start private, widen to pub(super) or pub(crate) when another module needs the item, and use pub only for things you intend to support.
Visibility of fields, variants, and trait items
Visibility does not flow downward automatically for every item kind. The rules differ.
Struct fields
Making a struct pub does not make its fields pub. Each field has its own visibility, and it is private by default.
mod account {
pub struct Account {
pub owner: String,
balance: u64,
}
impl Account {
pub fn new(owner: &str) -> Self {
Account {
owner: owner.to_string(),
balance: 0,
}
}
pub fn deposit(&mut self, amount: u64) {
self.balance += amount;
}
pub fn balance(&self) -> u64 {
self.balance
}
}
}
fn main() {
let mut a = account::Account::new("Ana");
a.deposit(50);
println!("{} has {}", a.owner, a.balance());
// a.balance = 1_000_000; // error[E0616]: field `balance` of struct `Account` is private
// let b = account::Account { owner: "Bo".to_string(), balance: 5 }; // error[E0451]
}A private field has two consequences. Code outside the module cannot read or write the field. It also cannot construct the struct with a struct literal, because the literal would have to name the private field. That is why new exists. This is how you enforce invariants: a balance that only changes through deposit cannot be set to nonsense from outside.
The same applies to tuple structs. In pub struct Id(u32); the field is private, so Id(5) fails outside the module because the constructor function is treated as private. Write pub struct Id(pub u32); to allow it, as the Square(pub u32) example in the module-files chapter does.
Enum variants
Enum variants are different: they take the visibility of the enum. A pub enum has public variants, and you cannot mark an individual variant pub. The fields inside a variant are also public.
mod light {
pub enum Signal {
Red,
Green,
Timed { seconds: u32 },
}
}
fn main() {
let s = light::Signal::Timed { seconds: 30 };
match s {
light::Signal::Timed { seconds } => println!("{seconds}s"),
light::Signal::Red | light::Signal::Green => println!("fixed"),
}
}If you need to hide the representation, wrap a private enum inside a struct with a private field.
Trait items and impls
Items declared in a trait are as visible as the trait itself, so you do not write pub on trait methods. For the same reason you cannot write pub on methods in an impl Trait for Type block. Inherent methods (in a plain impl Type block) do need pub individually, as deposit did above.
Visibility and re-exports
A use declaration is itself an item with a visibility. A plain use is private to its module. Writing pub use re-exports the name at a new path, which is how a library presents a short public API over a deeper internal layout.
A re-export cannot widen what the original allows. You cannot pub use an item that is only pub(crate) and make it public to other crates; the compiler rejects it. The next chapters build on this when shaping a public API.
Common errors
- E0603, "is private". A path crosses a module or item that is not visible from where you are. Read the message carefully: it names the first private segment, which might be a module in the middle of the path rather than the final function.
- E0616, "field is private". You accessed a field directly. Add an accessor method or make the field
pub, depending on whether the invariant matters. - E0451, "field is private" in a literal. You built a struct with a literal from outside its module. Add a constructor function.
- Public item in a private module. A
pub fninside a non-pubmodule is not reachable from other crates unless you re-export it. It behaves likepub(crate)in practice, and the compiler can warn that it is unused. - Private type in a public signature. A public function that returns or accepts a type the caller cannot name is an error or a lint, depending on the case. Make the type as visible as the functions that expose it.
Visibility and unit tests
The ancestor rule explains why unit tests can test private functions. A #[cfg(test)] mod tests is a child of the module it tests, so use super::*; brings the parent's private items into scope. Integration tests in the tests directory are separate crates and see only the public API. Choose where a test lives partly by what it needs to see.
Exercise
In the module tree crate::a::b, a function f in b is declared pub(super). Which of these can call f: the body of a, the crate root, a sibling module crate::a::c, a child module crate::a::b::d?
Show answer
The body of a, the sibling crate::a::c, and the child crate::a::b::d can call it. pub(super) makes f visible in a (the parent of b) and all descendants of a, which includes c and b::d. The crate root is not inside a, so it cannot call f. In practice c and the root also need the path to b to be visible, which it is for c because b is declared in a.
Exercise
Why does let acc = account::Account { owner: "Bo".to_string(), balance: 5 }; fail in main even though Account and owner are pub, and what is the standard fix?
Show answer
The field balance is private, and a struct literal must name every field, so code outside the account module cannot build the value (error E0451). The fix is to provide a public constructor such as Account::new, which lives inside the module and may set the private field.