crate and super
- Rust course
- Intermediate
- Lesson 75/115
- 4 min
Reach from the crate root or parent module with crate and super.
crate and super
Paths can be written as absolute or relative:
crate::— an absolute path starting from the crate root.super::— the parent module (like..in a file system).self::— the current module.
fn kok() -> i32 { 10 }
mod a {
pub fn ortak() -> i32 { 1 }
pub mod b {
pub fn f() -> i32 {
super::ortak() + crate::kok() // 1 + 10
}
}
}Which one when?
Between tightly coupled modules, super:: is used; the paths don't break when the code moves together. If something from elsewhere in the project is needed, crate:: is clearer. The same prefixes apply in use declarations:
mod rapor {
use crate::ayarlar::Ayar; // from elsewhere in the project
use super::ortak_bicim; // from a neighbour
}Practice Relative and absolute paths
Write the structure above: fn kok() -> i32 (10) at the root, ortak (1) inside mod a, and inside pub mod b an f returning super::ortak() + crate::kok(). Print the result of a::b::f().
Starter code
fn main() {
// buraya yaz
}Sample solution
fn kok() -> i32 {
10
}
mod a {
pub fn ortak() -> i32 {
1
}
pub mod b {
pub fn f() -> i32 {
super::ortak() + crate::kok()
}
}
}
fn main() {
println!("{}", a::b::f());
}Expected output
11
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Can a child module call a non-<code>pub</code> function in its parent with <code>super::</code>?
- Only with crate::
- Only in a test module
- Yes; child modules can see their ancestors' private items Correct answer
- No
Explanation: Privacy is free going upward, not downward. That's why a tests module reaches everything with use super::*;.
2 Parent module
pub fn f() -> i32 {
____::ortak() + crate::kok()
}
pub fn f() -> i32 {
super::ortak() + crate::kok()
}
Explanation: super refers to the parent module.
3 Prefix and starting point
| Term | Meaning |
|---|---|
crate:: |
Crate root |
super:: |
Parent module |
self:: |
Current module |
std:: |
Standard library |