Visibility controls which modules or crates can access a Rust item. Functions are private by default; add `pub` before a definition to make it public. A `use` statement brings a name into scope but does not make a private function accessible. section 5.1 section 5.4
Choose visibility to match the intended interface. Use `pub` for items that callers should access, and `pub(crate)` for helpers shared within a crate but hidden from other crates. A public item inside a private module is not necessarily accessible to external callers through that module. section 5.2.2 section 5.3
Listing 5.32 Final code for the forest crate
mod forest {
pub(crate) fn enter_area(area: &str) {
match area {
"tree cover" => println!("It's getting darker..."),
"witches coven" => println!("It's getting spookier..."),
"walking path" => println!("It's getting easier to walk..."),
x => panic!("Unexpected area: {}", x),
}
}
}
pub mod tree_cover {
pub fn enter() {
crate::forest::enter_area("tree cover");
}
}
pub mod walking_path {
pub fn enter() {
crate::forest::enter_area("walking path");
}
}
pub mod witches_coven {
pub fn enter() {
crate::forest::enter_area("witches coven");
}
}
The shared helper is visible throughout the crate, while public entry functions provide the external interface. section 5.3
Privacy also depends on the module tree. Nested modules can use private items in their parent modules, but parent modules cannot call private functions in child modules. This upward visibility lets sibling modules reach the private module at the crate root while `pub(crate)` makes its helper available within the crate. section 5.3 section 5.2.2
When exposing a function, check its signature as well. A public function returning a private error type can produce a compiler error: callers need access to the error type to use the interface. Marking both the function and the error enum public resolves the example below. section 4.5
Listing 4.14 Changes required in the calculate crate
...
pub enum Error {
InvalidNumber,
PopFromEmptyStack,
}
...
pub fn evaluate(problem: &str) -> Result<i32, Error> {
...
}
The calculator exposes both `evaluate` and its `Error` enum for use by another crate. section 4.5
For a function called from C, `pub` is one part of the declaration, not the whole interoperability setup. The example also uses `#[no_mangle]` to disable name mangling and `extern "C"` for C calling conventions. section 3.2.2
Listing 3.6 Rust solve function that can be exported as compatible with C
#[no_mangle]
pub extern "C" fn solve(
line: *const c_char, solution: *mut c_int) -> c_int {
0
}
The `solve` declaration combines public visibility with the annotations needed for the C interface. section 3.2.2
A `pub use` declaration can expose an item through an alias, giving callers a shorter path to it. section 5.2.2 section 5.4







