In Rust, access control levels determine which parts of a program can access a given item such as a function, variable, or module. Rust provides two access control levels: public and private.
1. Public Access Control Level: Items declared public can be accessed from outside of the module they are defined in. The ‘pub‘ keyword is used to make an item public. For instance, if we want to make a function or variable accessible from another module, we can use ‘pub‘ in the module that declares it.
// accessible from any module
pub fn public_function() {
// do something
}
pub const PUBLIC_CONSTANT: u32 = 5;
The ‘pub‘ keyword can control access at various levels of Rust’s module system - at the module level, the item level, or the field level. If we need to make all the items in a module public, we can use ‘pub mod‘ at the module-level to make everything therein accessible from other modules.
// accessible from any module
pub mod my_module {
pub fn public_function() {
// Do something
}
pub const PUBLIC_CONSTANT: u32 = 5;
}
2. Private Access Control level: Items declared as private are only accessible from within the same module where they are defined - that is, the items are not accessible from outside the module. Rust uses the absence of the ‘pub‘ keyword to signify that an item is private.
mod my_module {
fn private_function() {
// Do something
}
const PRIVATE_CONSTANT: u32 = 5;
}
The above code defines a module ‘my_module‘ that contains a private function ‘private_function‘ and a private constant ‘PRIVATE_CONSTANT‘, which can only be consumed within the ‘my_module‘ module.
To ensure privacy, Rust’s compiler will flag any attempt to access an item that has not been explicitly marked as public. So, if a private item should be accessed from another module, we will need to create an interface for it in the form of a public function or a public module.
For instance, the following code is attempting to access the private function ‘private_function‘ in ‘my_module‘ from the main module, and will result in a compile error:
// attempting to access a private function from another module
fn main() {
my_module::private_function(); // This will fail to compile
}
In conclusion, Rust’s access control levels provide a mechanism for encapsulation and data hiding by making it possible to restrict access to items defined within a module.