Sling Academy
Home/Rust/Navigating Visibility: pub vs Private Items in Rust Modules

Navigating Visibility: pub vs Private Items in Rust Modules

Last updated: January 04, 2025

When delving into the Rust programming language, understanding module visibility is a crucial aspect. Rust employs a powerful module system that allows you to encapsulate functionality, leading to better organization and reusability of code. Central to this system are the concepts of pub (public) and private items.

Module Basics

Rust splits code into modules, and each module can contain definitions of functions, structs, enums, traits, etc. By default, everything in Rust is private, which means it can only be accessed within its current module.

mod my_module {
    fn private_function() {
        println!("This function is private and only accessible within my_module.");
    }

    pub fn public_function() {
        println!("This function is public and accessible outside my_module.");
    }
}

In the above example, only public_function is accessible from outside the my_module due to the pub keyword. The private_function remains hidden within its module.

Understanding pub Keyword

The pub keyword in Rust is used to make components in a module visible outside of their declaring module. This allows library authors to expose parts of the code they wish to make available to library users, while keeping other parts internal.

mod outer_module {
    pub mod inner_module {
        pub fn inner_function() {
            println!("This is a public function inside an inner module.");
        }

        fn private_inner_function() {
            println!("This is a private function inside an inner module.");
        }
    }
}

fn use_functions() {
    outer_module::inner_module::inner_function();
    // outer_module::inner_module::private_inner_function(); // This line will cause a compile error
}

Private Access

All items, by default, are private in Rust, and this means they are restricted to the module where they are declared. However, private items can be accessed by any code within the same module, while public items can be accessed from outside the module.

Crate-level Visibility

You can also specify that a module or item should be visible within the entirety of the current crate by using the pub(crate) modifier. This means the visibility is restricted within the crate:

mod another_module {
    pub(crate) fn crate_visible_function() {
        println!("This function is visible throughout the crate.");
    }
}

fn another_function_in_crate() {
    another_module::crate_visible_function(); // Allowed access
}

mod not_accessible_outside {
    pub(crate) struct CrateVisibleStruct {
        pub field: i32,
    }
}

The use of pub(crate) is particularly useful when you want functionalities that should not be exposed in public APIs but still want to access throughout the library internally.

Using super and self for Access

The super and self keywords can be used to clarify the paths for accessing items within the module hierarchy. These are helpful in controlling scope:

mod main_module {
    mod sub_module_a {
        pub fn call_me() {
            println!("Called from sub_module_a!");
            super::sub_module_b::respond();
        }
    }

    mod sub_module_b {
        pub(super) fn respond() {
            println!("Response from sub_module_b!");
        }
    }
}

In this example, respond is accessible within its parent module, thus allowing sub_module_a to access it using super::. The use of self aids in absolute path references without starting at the crate root.

Conclusion

Rust’s module system of public and private items encourages mindful encapsulation and API design. By understanding how visibility modifiers affect your module hierarchy, you can design libraries and applications that are both robust and user-friendly.

Next Article: Understanding Cargo Workspaces for Multi-Crate Projects in Rust

Previous Article: Using submodules to Split Large Rust Files into Manageable Components

Series: Packages, Crates, and Modules in Rust

Rust

You May Also Like

  • E0557 in Rust: Feature Has Been Removed or Is Unavailable in the Stable Channel
  • Network Protocol Handling Concurrency in Rust with async/await
  • Using the anyhow and thiserror Crates for Better Rust Error Tests
  • Rust - Investigating partial moves when pattern matching on vector or HashMap elements
  • Rust - Handling nested or hierarchical HashMaps for complex data relationships
  • Rust - Combining multiple HashMaps by merging keys and values
  • Composing Functionality in Rust Through Multiple Trait Bounds
  • E0437 in Rust: Unexpected `#` in macro invocation or attribute
  • Integrating I/O and Networking in Rust’s Async Concurrency
  • E0178 in Rust: Conflicting implementations of the same trait for a type
  • Utilizing a Reactor Pattern in Rust for Event-Driven Architectures
  • Parallelizing CPU-Intensive Work with Rust’s rayon Crate
  • Managing WebSocket Connections in Rust for Real-Time Apps
  • Downloading Files in Rust via HTTP for CLI Tools
  • Mocking Network Calls in Rust Tests with the surf or reqwest Crates
  • Rust - Designing advanced concurrency abstractions using generic channels or locks
  • Managing code expansion in debug builds with heavy usage of generics in Rust
  • Implementing parse-from-string logic for generic numeric types in Rust
  • Rust.- Refining trait bounds at implementation time for more specialized behavior