Skip to content
Tutorials Center
My learning

Topics

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).

Rust
crate::config::load()   // absolute
self::helper()          // current module
super::shared()         // parent module

Try it

Rust Three kinds of path

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.

Rust self in use groups and Self in impls

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

Rust
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::x keeps working if the current file is moved; super::x keeps 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.
  • super at the root is an error; the crate root has no parent.
  • External crates are named directly (std::fmt, serde::Serialize). Use ::name to force an external crate when a local module has the same name.
  • self in a use group (use std::io::{self, Read}) imports the prefix itself; outside a group, use self::x refers to the current module.
  • Self vs self: Self is a type (inside impl and trait), while self is a value parameter or a module prefix. See Self.
  • Restricted visibility also uses these prefixes: pub(crate), pub(super), pub(self), pub(in crate::a).