Rust Programming: Paths into Scope with the use Keyword

0

The use keyword in Rust is used to bring paths into scope. This means that you can refer to items in the path without having to write out the full path every time. For example, if you have a module called `front_of_house` with a submodule called `hosting`, you can use the `use` keyword to bring `hosting` into scope. Then, you can refer to the `add_to_waitlist` function in `hosting` as simply `hosting::add_to_waitlist`. Here is an example of how to use the `use` keyword:

mod front_of_house {

    pub mod hosting {

        pub fn add_to_waitlist() {}

    }

}


use front_of_house::hosting;


pub fn eat_at_restaurant() {

    hosting::add_to_waitlist();

}

In this example, we use the `use` keyword to bring the `hosting` module into scope. Then, we can refer to the `add_to_waitlist` function in `hosting` as simply `hosting::add_to_waitlist`.

The `use` keyword can also be used to bring multiple paths into scope at once. For example, the following code brings the `hosting` and `greeting` modules into scope:

use front_of_house::{hosting, greeting};


pub fn eat_at_restaurant() {

    hosting::add_to_waitlist();

    greeting::say_hello();

}

Post a Comment

0Comments
Post a Comment (0)