🎓 A1Learner
🔍

Rust Module Paths

A Rust path is the full address of one item, written through the modules that contain it. A path joins module names with :: to reach the item.

An absolute path starts at the very top

A path names an item through its modules, joined by ::. An absolute path starts at the top. Use crate:: for your own crate. Or use the crate name for another crate, like std::collections::HashMap:

println!("{}", crate::kitchen::ticket());

super:: steps up to the parent

A relative path starts where you are. Inside chef, super:: steps up to its parent, kitchen — the module version of .. in a file path:

mod kitchen {
    pub fn ticket() -> &'static str { "ticket #7" }
    pub mod chef {
        pub fn serve() -> String { format!("chef serves {}", super::ticket()) }
    }
}
println!("{}", kitchen::chef::serve());

self:: means this module

A relative path may also begin with self:: — this module itself:

mod pantry {
    pub fn stock() -> String { format!("{} jars", self::jars()) }
    fn jars() -> i32 { 6 }
}
println!("{}", pantry::stock());

A right path can still be refused

The address below exists, but secret has no pub — the door is closed, and Rust stops you with error E0603:

mod kitchen {
    fn secret() -> &'static str { "shh" }
}
println!("{}", kitchen::secret()); // error E0603: function `secret` is private

Example

mod kitchen {
    pub fn ticket() -> &'static str { "ticket #7" }
    pub mod chef {
        pub fn serve() -> String { format!("chef serves {}", super::ticket()) }
    }
}
fn main() {
    println!("{}", kitchen::chef::serve());
    println!("{}", crate::kitchen::ticket());
}

Key points

  • Prefer absolute paths when the caller and the item may move separately.
  • Prefer super:: for a child that always moves together with its parent
  • Whether you may use it is a second question.
  • pub answers it.

In this example, kitchen holds a ticket function and a child module called chef. Inside chef, serve builds its text with super::ticket(). super steps up to the parent, kitchen. It calls its ticket function. The result is "chef serves ticket #7". Back in main, the first call uses the relative path kitchen::chef::serve. The second call spells the same kind of address from the very top: crate::kitchen::ticket prints "ticket #7". One item, two correct addresses — one starting where you stand, one starting at the root. The Visibility lesson covers that door-opening word in full.

Note

A path only finds an item.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

In a path, what does super:: mean?