From Mastadon post.
Working my way through the #rust book. Little confused by something in the modules section. Can't quite fit the whole thing in one toot, so here's a gist: <here>
Short version, useing nested modules. Does this allow access to ancestor modules or not?
In the modules section, the author refers back to the "guessing game" section and shows this:
use rand::Rng;
fn main() {
let secret_number = rand::thread_rng().gen_range(1..=100);
}
From this, I figure "oh ok. We've included Rng from the rand module. Then we use the thread_rng function which is in the rand module.
I guess because we've useed rand::Rng we now have access to public things in the rand module?
But then, testing this out, I do this:
// src/main.rs
use module_test::foo::bar;
fn main() {
println!("{}", foo::get_3());
println!("{}", bar::get_5());
}
// src/lib.rs
pub mod foo {
pub fn get_3() -> u32 { 3 }
pub mod bar {
pub fn get_5() -> u32 { 5 }
}
}
This fails to compile with error: use of undeclared crate or module foo
So what gives? If I use foo::bar::baz, does that allow me to do things off of foo itself or not?
Seems like not. But if not, then how does the use rand::Rng allow us to then access rand::other_non_Rng_things?
So you can always use a fully qualified list. In this case
rand::thread_rngis a function, nouseis even necessary to get it.However, the
usestatement is for pulling in theRngimplementation of things that adds methods likegenandgen_rangeto theThreadRngreturned bythread_rng. It's a bit of a trick.use rand::Ringisn't giving you access to anything so much as it's pulling in the definition of methods on theThreadRngstruct so that they exist (e.g,gen_range). You always have access to public function on modules as long as you fully qualify themIn your examples, you would be able to do:
or
For a bigger example:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=c5d2b44c45eddd78c98379b8ef033420