Public vs Private Visibility Rules
Public vs Private Visibility Rules
In Rust, everything is private by default. To expose items, use pub: - pub: Public to everyone. - pub(crate): Visible within the current crate only. - pub(super): Visible to the parent module.
mod orders {
pub struct Order {
pub id: u64,
secret_notes: String, // Private field!
}
impl Order {
pub fn new(id: u64, notes: String) -> Self {
Self { id, secret_notes: notes }
}
}
}
fn main() {
let o = orders::Order::new(1, String::from("VIP customer"));
println!("Order ID: {}", o.id);
// println!("{}", o.secret_notes); // ERROR: private field
}