9.12 Visibility and Modules
By default, structs and their fields are private to the module they are defined in. Use pub to expose them.
// In module `geometry`
pub struct Shape { // Public struct
pub name: String, // Public field
sides: u32, // Private field (default)
}
struct InternalData { // Private struct (default)
pub value: i32, // allowed, but pub has no effect
config: u8,
}
impl Shape {
pub fn new(name: String, sides: u32) -> Self { // Public constructor
Shape { name, sides }
}
// ... methods ...
}
Key visibility rules:
pub struct: Makes the struct type usable outside its defining module.pub field: Makes a field accessible outside the module if the struct itself is accessible.- Private fields/methods: Cannot be accessed directly from outside the module, even if the struct type is public. Access is typically provided via public methods (like getters/setters).
pubfield in a private struct: A field markedpubinside a struct that is notpubhas no effect.
This system enforces encapsulation, allowing modules to control their public API.