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, use
ing 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 use
ed 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_rng
is a function, nouse
is even necessary to get it.However, the
use
statement is for pulling in theRng
implementation of things that adds methods likegen
andgen_range
to theThreadRng
returned bythread_rng
. It's a bit of a trick.use rand::Ring
isn't giving you access to anything so much as it's pulling in the definition of methods on theThreadRng
struct 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