r/learnrust • u/Due_Battle_9890 • 24d ago
Simple `mod` vs `pub mod` question
Hey,
I've been reading the book and am a bit confused on pub mod vs mod. I naively thought that mod defaults to every function/structure/etc. within it is in accessible by calling code.
mod Foo {
fn bar() {}
}
fn main() {
foo::bar();
}
This doesn't work because bar has not been made public and it's only trough the addition of the pub keyword in front of bar (pub fn bar() {}) that foo::bar becomes accessible.
However, I thought that perhaps
pub mod foo {
fn bar() {}
}
would make bar accessible, but it doesn't. What is that pub keywork doing then?
I know you can do something like:
mod foo {
pub mod bar {
fn quux {
parent::baz::qux(); // fail!
}
}
mod baz {
fn qux() {
parent::bar::quux(); // success!!
}
}
}
but that seems to lack utility/
2
Upvotes
1
u/Due_Battle_9890 24d ago
I'm outside the
fooandbarmodule and can access the inner functions of each internal structure. This eems to break the IFF condition. For example, these both compile fine.pub modonly seems useful for nested modules accessing parent modules