module-concept

Rust Public structs and private fields

Expose useful operations while keeping representation details controlled. A public struct does not automatically make all its fields public; a constructor can enforce an invariant. Expected result (not executed): 8 1 Why: Callers can read id and use the accessor, but cannot directly access seats. Common mistake: Trying to construct a struct from another module using private fields.

Formal Syntax & Structure

rust syntaxrust
pub struct Ticket { pub id: u32, secret: u32 }

Working Example

Example Snippetrust
mod tickets {    pub struct Ticket { pub id: u32, seats: u32 }    impl Ticket {        pub fn new(id: u32) -> Self { Self { id, seats: 1 } }        pub fn seats(&self) -> u32 { self.seats }    }}fn main() { let t = tickets::Ticket::new(8); println!("{} {}", t.id, t.seats()); }
Rust Reference