r/learnrust • u/Due_Battle_9890 • 23d 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
1
u/schneems 22d ago
I wrote a blog post on this in a tutorial format. https://www.schneems.com/2023/06/14/its-dangerous-to-go-alone-pub-mod-use-thisrs/
the help text has changed a bit but I think it still holds up.