Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Keywords and Statements

The pub keyword

Reference for Rust pub: private by default, pub(crate), pub(super), pub(in path), fields, enum variants, trait items, and re-exporting with pub use.

Everything in Rust is private by default: an item is visible inside the module that defines it and in that module's descendants. pub widens the visibility. Plain pub makes an item visible to anyone who can reach its parent module, while the restricted forms pub(crate), pub(super), pub(self) and pub(in path) stop at a chosen boundary.

Visibility applies to functions, structs and their fields, enums (no per-variant visibility), modules, constants, statics, type aliases, traits and use declarations.

Rust
pub struct Config {
    pub name: String,
    pub(crate) retries: u32,
    secret: String,
}

Try it

Rust Levels of visibility

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Private fields and constructors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
pub item
pub(crate) item
pub(super) item
pub(self) item          // same as no modifier
pub(in path::to::ancestor) item
Form Visible in
(nothing) The current module and its descendants.
pub Everywhere the parent module is visible.
pub(crate) The current crate only.
pub(super) The parent module and its descendants.
pub(in path) The named ancestor module (it must be an ancestor) and its descendants.

Usage notes

  • Fields default to private, even in a pub struct. A struct with a private field cannot be built with a literal outside its module; provide a constructor function.
  • Enum variants and the fields inside them take the visibility of the enum; they cannot be marked individually.
  • Trait items (methods, associated types) are as public as the trait. Items in impl Trait for T take no pub.
  • Inherent impl methods need their own pub; the impl block itself has no visibility.
  • Private types in public signatures produce a warning or error (the private_interfaces lint), because callers could not name them.
  • pub use re-exports an item under a new path, which lets you reorganize internals without breaking users.
  • pub(crate) is the most useful restriction in libraries: share between your own modules, keep out of the public API. A pub item inside a private module is also not reachable from outside unless re-exported.
  • #[non_exhaustive] on a public struct or enum lets a library add fields or variants later without a breaking change.