Start Coding

Rust Visibility Rules

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.

Understanding Visibility in Rust

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.

Public vs. Private

  • Private: Accessible only within the current module
  • Public: Accessible from outside the current module

Visibility Rules in Action

Let's explore how visibility rules work with different Rust elements:

1. Modules


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.

2. Structs and Enums

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.

Best Practices

  • Make items public only when necessary
  • Use private fields with public getter methods for controlled access
  • Consider using the pub(crate) visibility modifier for crate-level visibility

Advanced Visibility Rules

Rust offers more granular control over visibility with additional modifiers:

  • pub(crate): Visible within the current crate
  • pub(super): Visible in the parent module
  • pub(in path): Visible in a specific path

Related Concepts

To 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.