Absolute path and crate name

Hi,

per documentation (Paths for Referring to an Item in the Module Tree - The Rust Programming Language) an absolute path is defined as follows:

* An *absolute path* starts from a crate root by using a crate name or a literal `crate` .

per documentation (Packages and Crates - The Rust Programming Language) the name of the src/main.rs crate is:

If a package contains src/main.rs and src/lib.rs, it has two crates: a library and a binary, both with the same name as the package.

Now if we create a package with a name 'restaurant' per the above the binary crate (src/main.rs) should have a name 'restaurant'. If we have the following code:

src/main.rs

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

fn main() {
    println!("Hello world!")
}

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

    // Alternative Absolute path
    restaurant::front_of_house::hosting::add_to_waitlist();

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

In this case the absolute path works which is:

crate::front_of_house::hosting::add_to_waitlist();

However if I try to use the name of the crate which is the package name (restaurant) instead of the literal name 'crate' it does not work. So alternative absolute path is not accepted:

restaurant::front_of_house::hosting::add_to_waitlist();

Can someone clarify where my I'm going wrong?

Thanks in advance!

The name of the crate only applies when you have both src/main.rs and src/lib.rs. You would use restaurant to access things in lib.rs from main.rs, whereas you use crate when it is in the same crate.

2 Likes

You also use the name of the crate in example programs. I guess the aim is to use the library in the same conditions as an external program in another crate.

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.