Rust Reference ยท Keywords and Statements
The crate, self and super path prefixes
Reference for crate, self and super in Rust paths: absolute and relative module paths, the $crate macro variable, Self versus self, and use self in groups.
Three keywords start a path inside the module tree. crate:: begins at the root of the current crate, self:: begins at the current module, and super:: begins at the parent module. They give you absolute and relative paths that keep working when a module moves, or when an external name with the same spelling exists.
They are valid in expressions, types, patterns and in use declarations. Do not confuse the lowercase self (a module path or a method receiver) with Self (the implementing type).
crate::config::load() // absolute self::helper() // current module super::shared() // parent module
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
crate::a::b self::a::b super::a super::super::a use self::a::b; use crate::a::{self, b}; $crate::path // inside macro_rules! only
| Prefix | Meaning |
|---|---|
crate |
The root module of the crate that contains this code. |
self |
The module in which the path appears. Optional in most cases. |
super |
The parent of the current module. May be repeated: super::super::x. |
$crate |
In macro_rules!, the crate that defines the macro, even when it is expanded elsewhere. |
Usage notes
- Absolute or relative?
crate::xkeeps working if the current file is moved;super::xkeeps working if the whole subtree is moved. Pick the one that expresses intent. - Privacy interaction:
super::private_fn()is allowed, because a child module may use its ancestors' private items. superat the root is an error; the crate root has no parent.- External crates are named directly (
std::fmt,serde::Serialize). Use::nameto force an external crate when a local module has the same name. selfin ausegroup (use std::io::{self, Read}) imports the prefix itself; outside a group,use self::xrefers to the current module.Selfvsself:Selfis a type (insideimplandtrait), whileselfis a value parameter or a module prefix. SeeSelf.- Restricted visibility also uses these prefixes:
pub(crate),pub(super),pub(self),pub(in crate::a).