In Rust, visibility determines which modules can access items (functions, structs, traits, modules, etc.). By default, all items are private, meaning they are only accessible within the module where they are defined and its descendant modules. TheDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
pub keyword modifies this boundary, exposing items to broader scopes.
Applying pub to an item makes it publicly accessible relative to its parent module. An item can be accessed outside the crate if it and all of its ancestor modules up to the crate root are marked pub. Alternatively, an item defined inside a private module can be made accessible outside the crate by re-exporting it using pub use from a public module. Re-exporting aliases the item into the new scope, allowing developers to expose internal items through a public-facing module facade without making the internal module structure public.
Restricted Visibility Modifiers
Rust provides path-based visibility modifiers to restrict access to specific scopes, allowing for granular encapsulation.pub(crate): Makes the item visible anywhere within the current crate, but not to external crates.pub(super): Makes the item visible only to the immediate parent module.pub(in path::to::module): Makes the item visible only within the explicitly specified module path. The specified path must be an ancestor of the current module.
Structs, Enums, and Inherent Implementations
Visibility rules apply differently to the internal components of custom data types and their implementations. Structs: Marking a struct aspub makes the type itself public, but its fields remain private by default. To allow access or instantiation using struct literal syntax outside of the defining module hierarchy, individual fields must be explicitly marked pub.
Enums: Marking an enum as pub automatically makes all of its variants public. Visibility modifiers cannot be applied to individual enum variants.
Inherent Implementations: Methods and associated functions defined within an inherent impl block (e.g., impl User { ... }) are private by default. They must be individually marked pub to be callable outside the module where they are defined.
Trait Visibility
When a trait is markedpub, all of its methods and associated items are inherently public. Visibility modifiers cannot be applied to individual methods within a trait definition or within an impl block for a trait.
The usability of a trait implementation is strictly constrained by the visibility of the trait itself. If a trait is private, its implementations cannot be accessed or used outside the module hierarchy where the trait is defined, even if the concrete type implementing the trait is public.
Master Rust with Deep Grasping Methodology!Learn More





