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







