Module 8 • Lesson 42

Paths and use Declarations

📚 7 min💻 Free🦀 nixus.pro

Paths and use Declarations

// Absolute path: from crate root
use std::collections::HashMap;
use std::io::{self, Read, Write}; // Multiple items from same module

// Relative path
mod front_of_house {
    pub mod hosting {
        pub fn add_to_waitlist() { println!("Added!"); }
    }
}

fn eat_at_restaurant() {
    // Absolute path
    crate::front_of_house::hosting::add_to_waitlist();

    // Relative path
    front_of_house::hosting::add_to_waitlist();

    // After use:
    use front_of_house::hosting;
    hosting::add_to_waitlist();
}

// Naming conflicts: use as
use std::fmt::Result as FmtResult;
use std::io::Result as IoResult;

// Glob import (be careful!)
use std::collections::*; // Imports everything

// Nested use
use std::{cmp::Ordering, io};

fn main() {
    let mut map = HashMap::new();
    map.insert("key", "value");

    // std prelude is automatically imported:
    // Vec, String, Option, Result, Box, etc. do NOT need use
    let v: Vec = Vec::new();
    let s: Option = None;
}

🎯 Practice

  1. Create nested modules and practice using both absolute and relative paths
  2. Use as to resolve naming conflicts between two imported types with the same name
  3. Re-export a commonly used type with pub use to simplify your API

🎉 Key Takeaways