Rust Programing: Idiomatic use Paths

0

Creating idiomatic use paths is the practice of bringing items into scope with the `use` keyword in a way that is consistent with the Rust community's conventions. One of the most important idiomatic use paths is to bring functions into scope by specifying their parent module. This makes it clear that the function is not locally defined, while still minimizing repetition of the full path. For example, the following code is idiomatic:

use crate::front_of_house::hosting;


fn eat_at_restaurant() {

    hosting::add_to_waitlist();

}

This code brings the `hosting` module into scope, which means that we can refer to the `add_to_waitlist` function as `hosting::add_to_waitlist`. This is more idiomatic than specifying the full path to the function, which would be `crate::front_of_house::hosting::add_to_waitlist`.

Another idiomatic use path is to specify the full path when bringing structs, enums, and other items into scope. This makes it clear what the item is, and it also helps to avoid name collisions. For example, the following code is idiomatic:

use std::collections::HashMap;


fn main() {

    let mut map = HashMap::new();

    map.insert(1, 2);

}

This code brings the `HashMap` struct into scope from the `std::collections` module. This is more idiomatic than specifying the shortened path, which would be `std::hashmap::HashMap`.

The exception to these rules is when bringing two items with the same name into scope. In this case, it is necessary to specify the full path to each item in order to distinguish them. For example, the following code brings two `Result` types into scope, both of which have the same name.

use std::fmt;

use std::io;


fn function1() -> fmt::Result {

    // --snip--

}


fn function2() -> io::Result<()> {

    // --snip--

}

In this case, it is necessary to specify the full path to each `Result` type in order to distinguish them. The `function1()` function returns a `fmt::Result`, while the `function2()` function returns an `io::Result<()>`.

Post a Comment

0Comments
Post a Comment (0)