Visibility rules in Rust determine how different parts of your code can be accessed and used. These rules are crucial for maintaining encapsulation and creating well-structured programs.
By default, all items in Rust are private. This means they can only be accessed within the same module. To make items public, you use the pub
keyword.
Let's explore how visibility rules work with different Rust elements:
mod my_module {
pub fn public_function() {
println!("This function is public");
}
fn private_function() {
println!("This function is private");
}
}
fn main() {
my_module::public_function(); // OK
// my_module::private_function(); // Error: private function
}
In this example, public_function
can be called from outside the module, while private_function
cannot.
For structs and enums, you can control the visibility of individual fields:
pub struct Person {
pub name: String,
age: u32, // Private field
}
impl Person {
pub fn new(name: String, age: u32) -> Person {
Person { name, age }
}
pub fn get_age(&self) -> u32 {
self.age
}
}
Here, name
is public, but age
is private. We provide a public method get_age()
to access the private field.
pub(crate)
visibility modifier for crate-level visibilityRust offers more granular control over visibility with additional modifiers:
pub(crate)
: Visible within the current cratepub(super)
: Visible in the parent modulepub(in path)
: Visible in a specific pathTo deepen your understanding of Rust's visibility rules, explore these related topics:
Mastering visibility rules is essential for creating well-organized and maintainable Rust code. It allows you to control access to your code's internals while providing a clean public API for others to use.