Sub topic 4
Controlling visibility with pub
This chapter assumes you can write functions and structs, and that you know what a module is and how the module tree is shaped. It covers how Rust decides which code can see which items.
The default is private
Every item is private unless you mark it otherwise. A private item can be used in the module that defines it and in that module's descendants. It cannot be used by the parent or by sibling modules. A child module can therefore use its ancestors' private items, but an ancestor cannot reach into its children.
mod shapes {
pub struct Rect {
pub width: u32,
pub height: u32,
}
impl Rect {
pub fn area(&self) -> u32 {
self.width * self.height
}
}
fn private_helper() -> u32 {
42
}
pub fn answer() -> u32 {
private_helper()
}
}
fn main() {
let r = shapes::Rect { width: 3, height: 4 };
println!("{}", r.area());
println!("{}", shapes::answer());
// shapes::private_helper(); // error: function `private_helper` is private
}answer is public, and it calls the private helper from inside shapes. This is the usual pattern. You keep the implementation private and expose a small set of functions.
Restricted visibility
Plain pub means "visible wherever the parent module is visible." Rust also lets you limit the audience.
| Modifier | Visible to |
|---|---|
| (none) | The current module and its descendants |
| `pub(self)` | Same as no modifier |
| `pub(super)` | The parent module and its descendants |
| `pub(crate)` | Everything in the current crate |
| `pub(in path)` | The named ancestor module, for example `pub(in crate::network)` |
| `pub` | Anyone who can reach the module path, including other crates if the path is public |
pub(crate) is the one you will use most. It marks internal helpers that several modules need but that should not be part of the library's public API.
mod network {
pub(crate) fn connect() -> &'static str {
"connected"
}
pub(super) fn secret_port() -> u16 {
8080
}
mod driver {
pub(super) fn init() -> u8 {
1
}
}
pub fn start() -> u8 {
driver::init()
}
}
fn main() {
println!("{}", network::connect());
println!("{}", network::secret_port());
println!("{}", network::start());
}main lives in the crate root, which is the parent of network, so it can call secret_port. It cannot call network::driver::init, because driver is itself private.
Visibility of fields and variants
Visibility applies separately to each struct field. A pub struct with a private field cannot be built with struct literal syntax outside its module, so the module must provide a constructor.
mod account {
pub struct Account {
pub owner: String,
balance: u32,
}
impl Account {
pub fn new(owner: &str) -> Account {
Account { owner: owner.to_string(), balance: 0 }
}
pub fn balance(&self) -> u32 {
self.balance
}
}
}
fn main() {
let a = account::Account::new("Ada");
println!("{} has {}", a.owner, a.balance());
// println!("{}", a.balance); // error: field `balance` is private
}This lets the module enforce invariants. Outside code cannot set balance to an invalid value, because it can only go through your functions.
Enums work differently. If an enum is pub, all of its variants are public too, and you cannot hide individual variants.
Why this matters for testing
A child module can see its parent's private items. That is why a #[cfg(test)] mod tests block with use super::*; can test private functions. Integration tests live outside the crate and see only what is public, so your visibility choices decide what each kind of test can reach.
Exercise
In a library crate, module db has a function marked pub(crate). Can another crate that depends on your library call it? Can a sibling module api in the same crate?
Show answer
Another crate cannot call it, because pub(crate) limits visibility to the defining crate. The sibling module api can, as long as api can name the path to db, for example crate::db::function_name, and db itself is visible to it.