liveBook · Manning

Public visibility

As explained in Learn Rust in a Month of Lunches

Visibility is the Rust access-control property that determines whether an item or field can be referenced from a given module or crate.

Public visibility controls whether Rust code can be referenced from another module or crate. Everything starts private, so use the pub keyword when other code needs access. Modules also provide boundaries that keep implementation details encapsulated. section 14.1 section 14.4

Making a function public

A function declared as fn prints_one_thing(...) remains private, so importing it from main produces an E0603 private-function error. Changing the declaration to pub fn makes the import and calls compile, printing 6 and a string. section 14.1.1

The effect of pub depends on the item it modifies:

  • Structs: pub exposes the type, but each field stays private unless it is also declared pub. section 14.1.2
  • Enums: pub makes every variant public, allowing callers to choose among them. section 14.1.2
  • Traits: pub makes every trait method public. section 14.1.2
  • Modules: nested modules need pub to be accessible from outside their containing module or crate. section 14.1 section 14.1.2
mod print_things {
 
    #[derive(Debug)]
    pub struct Billy {                               #1
        name: String,
        pub times_to_print: u32,
    }
 
    impl Billy {
        pub fn new(times_to_print: u32) -> Self {    #2
            Self {
                name: "Billy".to_string(),           #3
                times_to_print,
            }
        }
        pub fn print_billy(&self) {
            for _ in 0..self.times_to_print {
                println!("{}", self.name);
            }
        }
    }
}
 
fn main() {
    use print_things::*;
 
    let my_billy = Billy::new(3);                    #4
    my_billy.print_billy();
}

Shows a public struct with a private name, a public field, public methods, and a constructor that preserves the intended name. section 14.1.2

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains defaults, compiler feedback, and item-specific rules, but stops short of advanced visibility forms.
Examples
Uses a printing module, an E0603 diagnostic, and a Billy struct with selective field visibility.
What you can do after
Apply Rust pub declarations to expose functions, types, fields, methods, variants, and modules selectively.
How it connects
Connects visibility with modules, crates, encapsulation, structs, enums, traits, and fields.

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 Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.