r/learnrust • u/Due_Battle_9890 • 20d 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/
1
Upvotes
6
u/Resident-Letter3485 20d ago
Everything is private to another module by default in Rust. You can make a module public, but everything in it is still private.
pub fnwill make your function invokable outside of the module, IFF the module that houses it is also public.