A `use` declaration brings a name from a module or crate into the current scope. After moving greeting functions into `input` and `output` modules, calls such as `get_name()` no longer resolve in `main`. Adding `use input::get_name;` makes that name available there without changing the call. section 5.1
Three distinctions help when adding imports:
- Group names from one module with braces: `use output::{goodbye, hello};`. The calls can then use `goodbye()` and `hello()`. section 5.1
- An import does not make a private function accessible. Functions in another module must be marked `pub` before these imports work. section 5.1
- Adding an external crate is a separate step: declare the dependency in `Cargo.toml`, then import its names where needed, as with `use libc::{c_char, c_int};`. section 3.2.1
Paths in `use` can start at the crate root. For example, `use crate::treats::Treat;` lets code in another module write `Treat` rather than repeat `crate::treats::Treat`. Keeping the full path in the import makes the remaining code shorter and less dependent on its place in the module hierarchy. section 5.2.1
Listing 5.15 Using both relative and absolute paths
pub mod treats {
pub mod shop {
use crate::treats::Treat;
fn buy() -> Treat {
Treat::IceCream
}
}
pub enum Treat {
Candy,
IceCream,
}
pub struct ConsumedTreat {
treat: Treat,
}
fn eat(treat: Treat) -> ConsumedTreat {
ConsumedTreat { treat }
}
}
use crate::treats::ConsumedTreat;
fn regret(treat: ConsumedTreat) {
println!("That was a mistake");
}
Compare the crate-root paths in the `use` declarations with the short type names used by the functions. section 5.2.1
Expose a shorter public path
`pub use day_kind::DayKind;` brings `DayKind` to the crate root as a public-facing name. Other modules can then write `use crate::DayKind;` instead of `use crate::day_kind::DayKind;`. A library can use the same pattern to spare callers a deeply nested path. section 5.2.2
