Module confusion

While going through the modules and crate part of the rust programming language book, I got a little bit confused regarding the verbiage used to convey how functions are accessed from their modules.

mod front_of_house {
    pub mod hosting {
        pub fn add_to_waitlist() {}
    }
}

pub fn eat_at_restaurant() {
    // Absolute path
    crate::front_of_house::hosting::add_to_waitlist();

    // Relative path
    front_of_house::hosting::add_to_waitlist();
}

The above snippet is put in the crate root file at src/lib.rs. The book then says something like this:

The front_of_house module isn’t public, but because the eat_at_restaurant function is defined in the same module as front_of_house (that is, eat_at_restaurant and front_of_house are siblings), we can refer to front_of_house from eat_at_restaurant.

But how is eat_at_restaurant defined in the same module as front_of_house ? It's clearly defined outside front_of_house module. Were they trying to say that they're defined in the same file or something? Can any of you guys help me understand this?

Thanks in advance!

Module front_of_house and function eat_at_restaurant are both defined in the root module of the crate (which corresponds to file lib.rs).

1 Like

Think of a module as an item just like a function, it is clear that two functions foo and bar can refer to each other when they are both defined in the same module (in this case, the root module of the crate), even though they are both private.

fn main(){
    bar();
}
fn foo(){
    println!("foo");
}

fn bar(){
    foo();
}

By the same token:

fn main() {
    bar();
}

mod my_mod {
    pub fn foo() {
        println!("foo");
    }
}

fn bar() {
    my_mod::foo();
}

bar can refer to foo even though it is inside the private module my_mod, because they both (bar and my_mod) reside in the same module. Just treat modules like any other item and you'll get it right.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.