Sub topic 3
Paths and use declarations
This chapter assumes you can write functions, structs, and Result code, and that you know what mod and pub do from the earlier chapters on modules and the module tree. Here you will learn how the compiler resolves a name to an item and how use shortens those names.
What a path is
A path is a sequence of names separated by :: that points at an item such as a function, struct, enum, trait, or module. The compiler resolves every path against the module tree. A path comes in two forms.
- An absolute path starts at a fixed root. Inside your own crate the root is the keyword
crate. For an external crate or the standard library, the root is that crate's name, such asstd. - A relative path starts at the current module. It begins with a name that is in scope, or with
self(the current module) orsuper(the parent module).
| Path | Starts from | Example |
|---|---|---|
| `crate::a::b` | Root of the current crate | `crate::garden::vegetables::plant()` |
| `std::mem::swap` | A named external crate | `std::mem::swap(&mut x, &mut y)` |
| `self::b` | Current module | `self::helper()` |
| `super::b` | Parent module | `super::water_amount()` |
| `b::c` | A name in scope here | `vegetables::plant()` |
Absolute and relative paths in practice
The program below uses all three styles. The module tree it builds is drawn after the code.
mod garden {
pub mod vegetables {
#[derive(Debug)]
pub struct Carrot {
pub length: u32,
}
pub fn plant() -> Carrot {
Carrot { length: 1 }
}
pub fn grow(c: &mut Carrot) {
c.length += super::water_amount();
}
}
fn water_amount() -> u32 {
2
}
pub fn tend() -> u32 {
let mut c = vegetables::plant();
crate::garden::vegetables::grow(&mut c);
c.length
}
}
fn main() {
println!("{}", garden::tend());
}This prints 3. In tend, vegetables::plant() is relative, because vegetables is a child of the module that contains tend. The call to grow is absolute. In grow, super::water_amount() reaches the private function in the parent module. That is allowed because code inside a module may use the private items of its ancestors.
Which style should you pick? Prefer absolute paths with crate:: when an item is likely to be moved on its own. If you move the caller, an absolute path still works. If you move the caller and the callee together, relative paths still work. Use super:: for close relatives, such as a child module reaching a helper in its parent.
Bringing names into scope with use
Writing long paths everywhere is tiresome. A use declaration creates a shortcut name in the current module, much like a symbolic link in a file system.
use std::collections::HashMap;
use std::fmt::{self, Display};
mod shapes {
pub mod circle {
pub fn area(r: f64) -> f64 {
3.14 * r * r
}
}
pub mod square {
pub fn area(s: f64) -> f64 {
s * s
}
}
}
use shapes::{circle, square};
struct Label(String);
impl Display for Label {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "<{}>", self.0)
}
}
fn main() {
let mut areas: HashMap<String, f64> = HashMap::new();
areas.insert("circle".to_string(), circle::area(1.0));
areas.insert("square".to_string(), square::area(2.0));
println!("{:.2} {:.2}", areas["circle"], areas["square"]);
println!("{}", Label("done".to_string()));
}The output is 3.14 4.00 and then <done>. Three features of use appear here.
- Nested groups.
use shapes::{circle, square};replaces two separate lines. selfin a group.use std::fmt::{self, Display};imports the modulefmtitself and the traitDisplay. That lets you write bothfmt::ResultandDisplay.- Relative
usepaths.use shapes::{...}starts withshapes, a name that exists in this module. This works in edition 2018 and later. Ausepath may begin with a crate name,crate,self,super, or any name already in scope.
The idiom: functions by module, types by full path
Rust style has a convention that you will see in most codebases.
- For functions, import the parent module and call
module::function(). The call site then shows that the function is not defined locally. This is why the example callscircle::area. - For structs, enums, and traits, import the item itself, as in
use std::collections::HashMap;. - When two items share a name, import their parent modules, or rename one with
as.
use std::fmt::Result as FmtResult;
use std::io::Result as IoResult;
fn fmt_ok() -> FmtResult {
Ok(())
}
fn io_ok() -> IoResult<()> {
Ok(())
}
fn main() {
fmt_ok().unwrap();
io_ok().unwrap();
println!("both ok");
}Without as, the second import fails with error E0252, because the name Result would be defined twice. You can also write use some::Trait as _;. This brings a trait's methods into scope without binding a name that could clash with another.
Where a use declaration applies
A use declaration applies only to the scope that contains it. This is the source of many beginner errors. Importing HashMap at the top of a file does not make it visible inside a child module of that file.
mod report {
use std::collections::HashMap;
pub fn empty() -> HashMap<String, u32> {
HashMap::new()
}
}
fn main() {
let m = report::empty();
println!("{}", m.len());
}The child module report needs its own use. If the parent had imported HashMap, the child could write use super::HashMap;. Test modules use the same mechanism when they write use super::*; to pull in everything from the parent.
You can also put use inside a function body. The import then lasts only for that block, which is useful for traits, because a trait's methods can be called only when the trait is in scope.
fn render(n: u32) -> String {
use std::fmt::Write;
let mut s = String::new();
write!(s, "n = {}", n).unwrap();
s
}
fn main() {
println!("{}", render(7));
}Without the use std::fmt::Write; line, write! on a String fails with E0599 ("no method named write_fmt found"), even though String implements the trait. The compiler's message usually suggests the missing import.
Glob imports
use std::collections::*; imports every public item from a module. Globs are convenient, but they hide where a name came from. A later upstream release can add an item that collides with one of your names. Reserve globs for two cases: use super::*; in a test module, and a crate's own prelude module. If a name you define locally has the same name as a glob-imported one, your local definition wins, which is quiet enough to cause surprises.
Privacy applies to every segment
Every module along a path must be reachable from where you stand. Each item along it must also be visible. The full rules are in the next chapter, but one point matters here. A use declaration is itself private to its module by default. Importing HashMap into module a does not let module b write a::HashMap. Making an import visible to others requires pub use, which a later chapter covers.
Reading the errors
| Error | Typical message | Usual cause |
|---|---|---|
| E0432 | unresolved import | Misspelled segment, missing `mod` declaration, or a missing dependency in `Cargo.toml` |
| E0433 | failed to resolve: use of undeclared crate or module | The first segment is not in scope in this module |
| E0425 | cannot find function in this scope | A needed `use` is missing, or you are calling `plant()` instead of `vegetables::plant()` |
| E0603 | function is private | A path segment lacks `pub` |
| E0252 | name defined multiple times | Two imports with the same final name; use `as` |
| E0599 | no method named ... found | The trait is not in scope |
A frequent cause of E0432 is a file that exists but is never declared. Creating src/util.rs does nothing until some module contains mod util;.
Exercise
A crate has the tree crate -> net -> http (module), where http contains pub fn get(), and a private function fn log() directly in net. Write the path that calls log from inside http::get, once as an absolute path and once as a relative path. Then explain why the call is allowed even though log is private.
Show answer
Absolute: crate::net::log(). Relative: super::log(). The call is allowed because privacy permits a module and its descendants to use the private items of its ancestors. http is a child of net, so code in http can see log. The reverse is not true: net cannot see private items inside http.
Exercise
Your file contains use std::fmt::Result; and use std::io::Result; and fails with E0252. Give two ways to fix it.
Show answer
Rename one import, for example use std::io::Result as IoResult;. Or import the parent modules, use std::fmt; and use std::io;, and write fmt::Result and io::Result at each use.