The crate keyword is a Rust path segment that refers to the root of the current crate. Use it to write an absolute path to an item inside the current crate, regardless of the module where the path appears. section 5.2.1
Choose the path form that matches the relationship between the current module and the target item:
- Use crate::treats::Treat for an absolute path from the current crate root. section 5.2.1
- Use super::Treat for a relative path to the namespace above the current module. section 5.2.1
- Make modules or items public with pub when code in another module must access them. section 5.2.1
Referencing a type from the crate root
Inside treats::shop, an absolute path can name the crate's Treat type directly: fn buy() -> crate::treats::Treat { crate::treats::Treat::IceCream }. The same relationship can use super::Treat because shop is nested directly inside treats. section 5.2.1
Listing 5.13 Life cycle methods in libsnack using absolute paths
pub mod treats {
pub mod shop {
fn buy() -> crate::treats::Treat {
crate::treats::Treat::IceCream
}
}
pub enum Treat {
Candy,
IceCream,
}
pub struct ConsumedTreat {
treat: Treat,
}
fn eat(treat: crate::treats::Treat) -> crate::treats::ConsumedTreat {
crate::treats::ConsumedTreat { treat }
}
}
fn regret(treat: crate::treats::ConsumedTreat) {
println!("That was a mistake");
}
Inspect the complete libsnack example, including crate-qualified parameter types, return types, and enum variants. section 5.2.1
