liveBook · Manning

Relative path

As explained in Refactoring to Rust

A Rust relative path identifies an item from the current namespace or another namespace relative to the location where the path appears.

A relative path identifies a variable or item from the current namespace. Unlike an absolute path, it is resolved from the module where it appears. section 5.2.1

Use relative paths to navigate nearby items in a Rust module hierarchy:

  • Write an item name such as `hello` for something in the current namespace. section 5.2
  • Use `super` to refer to the namespace above the current module, such as `super::Treat`. section 5.2.1
  • Refer to an item from the crate root with an absolute path such as `crate::treats::ConsumedTreat`; a relative alternative is `treats::ConsumedTreat` when resolved from the root. section 5.2.1
  • Keep visibility in mind: modules and items generally need `pub` to be accessed from another module. section 5.2.1

Choosing the shorter module-relative path

Inside `treats::shop`, `fn buy() -> super::Treat` returns the parent module's `Treat` type. The equivalent absolute form is `crate::treats::Treat`. At the crate root, `fn regret(treat: treats::ConsumedTreat)` uses a relative path to reach the nested type. section 5.2.1

Listing 5.14 Life cycle methods in libsnack using relative paths
pub mod treats {
  pub mod shop {
    fn buy() -> super::Treat {
      super::Treat::IceCream
    }
  }

  pub enum Treat {
    Candy,
    IceCream,
  }

  pub struct ConsumedTreat {
    treat: Treat,
  }

  fn eat(treat: Treat) -> ConsumedTreat {
    ConsumedTreat { treat }
  }
}

fn regret(treat: treats::ConsumedTreat) {
  println!("That was a mistake");
}

Compare relative paths with their absolute equivalents in a nested module example. section 5.2.1

How Refactoring to Rust covers it

How deep it goes
Defines resolution from the current namespace and demonstrates `super`, but does not descend into compiler name-resolution internals.
Examples
Demonstrates `hello`, `super::Treat`, `treats::ConsumedTreat`, and equivalent `crate::treats` paths in module listings.
What it assumes
Assumes basic Rust items and namespaces while introducing crates, modules, visibility, and the `super` and `crate` segments.
What you can do after
Apply relative paths to access items from current and parent modules in Rust programs.
How it connects
Connects relative paths with absolute paths, crates, modules, namespaces, and visibility.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Refactoring to Rust. The section links point to the parts of the book it draws on.