wiki/dev/lang/rust/Module.md

1.1 KiB

Module (access control).

Create module.

Separate file.

src/garden.rs

Separate dir.

src/garden/mod.rs

Inline / Access control.

Everything is private by default. Use keyword pub to make something public.

mod sausage_factory {
  fn get_secret_sauce() -> String {
    String::from("Ginger")
  }

  pub fn make_sausage() {
    get_secret_sauce();
    println!("sausage!");
  }
}

fn main() {
  sausage_factory::make_sausage();
}

Access module.

Use use and as keywords.

use std::io;
use std::io as IO;
use std::io::{self, Write};
use std::collections::*;
mod delicious_snacks {
  pub use self::fruits::PEAR as fruit;
  pub use self::veggies::CUCUMBER as veggie;

  mod fruits {
    pub const PEAR: &'static str = "Pear";
    pub const APPLE: &'static str = "Apple";
  }

  mod veggies {
    pub const CUCUMBER: &'static str = "Cucumber";
    pub const CARROT: &'static str = "Carrot";
  }
}

fn main() {
  println!(
    "favorite snacks: {} and {}",
    delicious_snacks::fruit,
    delicious_snacks::veggie
  );
}