skip to content

In Rust, what visibility do items and struct fields get by default, and what does marking them pub change?

level: juniorimportance: must knowfreq 76%

answer

  1. the module, not the type
  2. who else sees it: the children
  3. a pub struct keeps its fields
  4. two default-public exceptions
  5. E0603 and E0616

basics

~20 s

Every Rust item and struct field is private to its defining module and that module's descendants unless marked pub. Marking a struct pub leaves its fields private; only enum variants and pub trait items inherit their parent's visibility.

solid answer

~50 s

Rust's default is private, and privacy is measured in modules: a private item or field can be used by the module that declares it and by every module nested inside it, and by nothing else, not the parent, not a sibling, not another crate. `pub` makes an item usable from outside, but only when every module on the path to it is reachable too, so a `pub fn` inside a private module stays invisible to other crates unless something re-exports it. On a struct, `pub` works field by field: `pub struct Reading { pub label: String, samples: u32 }` exposes `label` and hides `samples`. The two exceptions are the variants of a `pub enum` and the items of a `pub trait`, which follow their parent. Calling a private function from outside is E0603; reading a private field is E0616.

code

rust · 27 lines
rust
mod temperature {
    pub struct Reading {
        pub label: String,
        samples: u32,
    }

    pub fn new_reading(label: &str) -> Reading {
        Reading { label: label.to_string(), samples: 0 }
    }

    fn round_to_tenth(c: f64) -> f64 {
        (c * 10.0).round() / 10.0
    }

    pub fn record(r: &mut Reading, celsius: f64) -> f64 {
        r.samples += 1;
        round_to_tenth(celsius)
    }
}

fn main() {
    let mut r = temperature::new_reading("boiler");
    let c = temperature::record(&mut r, 21.37);
    println!("{} {c}", r.label); // boiler 21.4
    // temperature::round_to_tenth(1.0); // error[E0603]: function `round_to_tenth` is private
    // println!("{}", r.samples);        // error[E0616]: field `samples` of struct `Reading` is private
}

go deeper

for a junior

Recall the rule in one line: private to the declaring module and its children unless pub. Then name the two exceptions, enum variants and pub trait items, and say that pub on a struct leaves its fields private.

for a middle

Explain that privacy is checked on every path, so a pub item behind a private module is still unreachable, and connect the errors: E0603 for a private item, E0616 for a field, E0624 for a method.

for a senior

Show you treat pub as a promise: each item a library exposes is one that removing later breaks, so keep the default and widen deliberately, often to pub(crate) first.

for a principal

Frame the default as cheap insurance: privacy is a boundary rustc enforces on every build at no runtime cost, so private-unless-needed keeps the public surface small enough to review each release.

## The rule: private to the module and its descendants Rust decides **visibility** by module, not by type and not by file. The Reference states the default in one sentence: *by default, everything is private*, with two exceptions covered below. "Private" has a precise meaning: a private item may be accessed by **the current module and its descendants**. So for an item declared in `crate::temperature`: - code inside `temperature` can use it; - code in any module nested inside `temperature` (for example `temperature::tests`) can use it, typically through `super::`; - the parent module, sibling modules and other crates cannot. Privacy flows downward only. A child can see everything its ancestors declare, but a parent cannot look into a child's private items. That is why a test module nested inside the module it tests can call private helpers, while the crate root cannot. ## What `pub` does and does not do Writing `pub` on an item makes it accessible from outside its module, under one condition: **every module on the path must be accessible too**. The Reference spells it out: a public item can be accessed from module `m` if you can access all of the item's ancestor modules from `m`. A `pub fn` inside a private `mod internal` declared at the crate root is therefore usable anywhere in the same crate (the whole crate descends from the root) but not from another crate, unless a `pub use` re-exports it. | Declaration inside `mod temperature` | Usable from the parent module? | Usable from another crate? | |---|---|---| | `fn round_to_tenth()` | no (E0603) | no | | `pub fn record()` | yes | only if `temperature` is reachable from the crate root, or via a re-export | | `pub struct Reading` with private `samples` | the type yes, `samples` no (E0616) | same, plus the path rule | | `pub enum Mode { Heat, Cool }` | the enum and both variants | same, plus the path rule | ## Struct fields are private one by one `pub` on a struct makes the **type** nameable outside the module; it says nothing about the fields. Each field has its own visibility and defaults to private. With `pub struct Reading { pub label: String, samples: u32 }`, outside code can read and write `label`, gets E0616 when it touches `samples`, and cannot write a `Reading { .. }` literal at all, because a literal has to set the private field (that last check, E0451, is how privacy protects a type's invariants). Methods follow the same default: an inherent method in `impl Reading` is private unless marked `pub`, and calling a private one from outside is E0624. ## The two exceptions 1. **Enum variants.** If the enum is `pub`, every variant, and every field inside a variant, is public with it. You cannot narrow one; writing `pub` on a variant is rejected with E0449 ("visibility qualifiers are not permitted here"). 2. **Trait items.** The methods, associated types and constants of a `pub trait` are public with the trait. A `pub` written on a method in a trait impl is also E0449, because that item already shares the trait's visibility. ## Reading the errors When privacy blocks a use, rustc names the kind of item in the message: - **E0603** "function `round_to_tenth` is private": a private item (function, constant, module, type) used outside its scope; - **E0616** "field `samples` of struct `Reading` is private": reading or assigning a private field; - **E0624** a private method called outside its module; - **E0451** a struct literal or pattern that names a private field. None of these is E0425 ("cannot find"): the name resolves, and the privacy check rejects the access afterwards. That difference is a quick tell in code review. ## Why a private default suits Rust Everything you mark `pub` in a library is something other crates may start to depend on, and removing it later breaks them. A private default means exposure is always a deliberate edit, and rustc then enforces the boundary for free on every build: there is no runtime check, no reflection escape hatch in safe code, and no convention to remember. Start private, widen to `pub(crate)` when other modules need an item, and to `pub` only when it truly belongs to the crate's interface.

  • Can a parent module call a private function defined in its child module in Rust?
    No. Privacy flows downward only: a private item is visible to the module that declares it and to that module's descendants. The parent of `temperature` cannot call `temperature::round_to_tenth` unless the function is marked `pub` or `pub(super)`, which means exactly 'visible to my parent'. The child, by contrast, can call any private item of its parent through `super::`.
  • Does marking a struct pub let another crate read all of its fields?
    Only the fields also marked `pub`. `pub struct` makes the type nameable; each field keeps its own visibility, so other code can read `label` but gets E0616 on `samples`. While any field is hidden, outside code cannot write a struct literal for the type either; that is rejected with E0451.
  • Is a method in an impl block of a pub struct public by default?
    No. Inherent methods carry their own visibility and default to private, so calling one from another module is E0624. Only the items of a `pub trait` are public by default, and writing `pub` on a method inside a trait impl is rejected with E0449 because it already follows the trait.

  • Marking a struct pub makes all of its fields public too.
  • Privacy is per type, so any impl block anywhere in the crate can read private fields.
  • A parent module can use every item declared in its child modules.
  • Enum variants need pub one by one, just like struct fields.
  • A pub fn is reachable from other crates even when its module is private and nothing re-exports it.