Modules

View saved

Declare a module inline

mod creates a namespace. pub exports items.

mod greetings {
    pub fn hello() {
        println!("hello");
    }
}

fn main() {
    greetings::hello();
}

Bring names into scope

use shortens paths.

use greetings::hello;
hello();

File modules

For larger projects, mod utils; loads utils.rs or utils/mod.rs.

Visibility habits

  • Items are private by default
  • Mark pub only for the API you want to share
  • Parent modules can access child private items; external crates cannot
  • Start with one file until structure is needed

Comments

One comment per signed-in account. Comments are saved with this page’s URL.