Visibility and re-exports
Quick answer
Visibility defines which parts of your program may access an item. Keep implementation details private and expose a small public interface that callers can rely on.
Public paths
Items are private by default, with exceptions such as trait items. pub(crate) restricts access to the crate; pub(super) to the parent module's scope. pub use can expose a public item through a new public path even if its enclosing module is private. A public struct's fields remain private unless separately exposed.
mod internal { pub fn version() -> u32 { 2 } }pub use internal::version;fn main() { println!("{}", version()); }Expected stdout (not executed):
2The caller need not name the internal module.
mod model { pub struct Account { balance: u32 } }fn main() { let _ = model::Account { balance: 5 }; }Expected: compilation fails; exact diagnostic not verified.
Expose a constructor that validates the balance instead.
Common mistake
Making a struct public does not make all its fields public.
Try it yourself
Create a private module with a public function and re-export the function under a different name.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Visibility and re-exports — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A public function is inside a private implementation module. How can callers get a stable public path?
Visibility and re-exports — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust mod internal { pub fn version() -> u32 { 2 } } pub use internal::version; fn main() { println!("{}", version()); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Visibility and re-exports — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust mod model { pub struct Account { balance: u32 } } fn main() { let _ = model::Account { balance: 5 }; } ``` Which outcome or interpretation best matches this example?