A relative path identifies a variable or item from the current namespace. Unlike an absolute path, it is resolved from the module where it appears. section 5.2.1
Use relative paths to navigate nearby items in a Rust module hierarchy:
- Write an item name such as `hello` for something in the current namespace. section 5.2
- Use `super` to refer to the namespace above the current module, such as `super::Treat`. section 5.2.1
- Refer to an item from the crate root with an absolute path such as `crate::treats::ConsumedTreat`; a relative alternative is `treats::ConsumedTreat` when resolved from the root. section 5.2.1
- Keep visibility in mind: modules and items generally need `pub` to be accessed from another module. section 5.2.1
Choosing the shorter module-relative path
Inside `treats::shop`, `fn buy() -> super::Treat` returns the parent module's `Treat` type. The equivalent absolute form is `crate::treats::Treat`. At the crate root, `fn regret(treat: treats::ConsumedTreat)` uses a relative path to reach the nested type. section 5.2.1
Listing 5.14 Life cycle methods in libsnack using relative paths
pub mod treats {
pub mod shop {
fn buy() -> super::Treat {
super::Treat::IceCream
}
}
pub enum Treat {
Candy,
IceCream,
}
pub struct ConsumedTreat {
treat: Treat,
}
fn eat(treat: Treat) -> ConsumedTreat {
ConsumedTreat { treat }
}
}
fn regret(treat: treats::ConsumedTreat) {
println!("That was a mistake");
}
Compare relative paths with their absolute equivalents in a nested module example. section 5.2.1
