liveBook · Manning

Crate keyword

As explained in Refactoring to Rust

The crate keyword is a Rust path segment that refers to the root of the current crate.

The crate keyword is a Rust path segment that refers to the root of the current crate. Use it to write an absolute path to an item inside the current crate, regardless of the module where the path appears. section 5.2.1

Choose the path form that matches the relationship between the current module and the target item:

  • Use crate::treats::Treat for an absolute path from the current crate root. section 5.2.1
  • Use super::Treat for a relative path to the namespace above the current module. section 5.2.1
  • Make modules or items public with pub when code in another module must access them. section 5.2.1

Referencing a type from the crate root

Inside treats::shop, an absolute path can name the crate's Treat type directly: fn buy() -> crate::treats::Treat { crate::treats::Treat::IceCream }. The same relationship can use super::Treat because shop is nested directly inside treats. section 5.2.1

Listing 5.13 Life cycle methods in libsnack using absolute paths
pub mod treats {
  pub mod shop {
    fn buy() -> crate::treats::Treat {
      crate::treats::Treat::IceCream
    }
  }

  pub enum Treat {
    Candy,
    IceCream,
  }

  pub struct ConsumedTreat {
    treat: Treat,
  }

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

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

Inspect the complete libsnack example, including crate-qualified parameter types, return types, and enum variants. section 5.2.1

How Refactoring to Rust covers it

How deep it goes
Defines absolute paths, contrasts them with relative paths and super, and demonstrates both forms in module code.
Examples
Uses a libsnack crate with treats, shop, Treat, ConsumedTreat, buy, eat, and regret examples.
What it assumes
Assumes basic Rust modules and teaches absolute paths alongside relative paths and module visibility.
What you can do after
Apply it via Rust module paths to name current-crate items from nested modules.
How it connects
Connects crate paths with modules, relative paths, super, visibility, and pub use.

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.