liveBook · Manning

Public visibility

As explained in Code Like a Pro in Rust

Visibility is a Rust access-control property that determines which modules and crates can access a declaration or struct field.

Use visibility to decide which modules and crates can access a declaration. Rust declarations are private by default: a private item is accessible within its module and submodules. Add `pub` only where access is needed. section 2.9

Choose the narrowest scope that serves the caller:

  • `pub` makes an item public; `pub(crate)` permits access within the crate but not from another crate. section 2.9
  • `pub(self)`, `pub(super)`, and `pub(in path)` restrict access to the named module scope. section 2.9
  • Visibility applies separately to a struct and each of its fields. Making a struct public does not make its fields public. section 4.5.3
mod private_mod {
 pub fn private_mod_fn() {}
}
pub mod public_mod {
 pub fn public_mod_fn() {}
}

Both functions are marked `pub`, but the function inside `private_mod` is not exported through that private module. A public item also needs a publicly accessible module path. section 2.9

pub struct MixedVisibilityStruct {    #1
  pub name: String,                   #2
  pub(crate) value: String,           #3
  pub(super) number: i32,             #4
}

The public struct gives its fields different access scopes: `name` is public, `value` is crate-visible, and `number` is visible from the parent module. section 4.5.3

Keep fields private unless callers need direct access or modification. Also avoid exporting unnecessary names: modules help contain namespace pollution. One default-privacy exception is that associated items of public traits and public enums are public by default. section 4.5.3 section 2.9

How Code Like a Pro in Rust covers it

How deep it goes
Explains private defaults, scoped `pub` modifiers, module-path limits, field-level visibility, and exceptions for public trait and enum items.
Examples
Contrasts public functions in private and public modules, then shows a public struct with fields using three visibility scopes.
What it assumes
Builds on module and struct declarations while explaining their visibility defaults.
What you can do after
Apply it to expose needed APIs while keeping other declarations and fields within narrower module or crate scopes.
How it connects
Connects visibility to modules, crates, struct fields, and namespace pollution.

Also explained in

Compare how 8 books explain public visibility →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Code Like a Pro in Rust. The section links point to the parts of the book it draws on.