[Rust] module with public and private methods / interfaces

Methods:

mod sausage_factory {
    // private method
    fn get_secret_recipe() -> String {
        String::from("Ginger")
    }

    // public method
    pub fn make_sausage() {
        get_secret_recipe();
        println!("sausage!");
    }
}

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

 

Interfaces:

mod delicious_snacks {
    // export those as interfaces
    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
    );
}

 

You can use the 'use' keyword to bring module paths from moudles from anywhere and especially from the Rust standard library into your scope.

Bring SystemTime and UNIX_EPOCH from the std::time module.

use std::time::{UNIX_EPOCH, SystemTime};

fn main() {
    match SystemTime::now().duration_since(UNIX_EPOCH) {
        Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
        Err(_) => panic!("SystemTime before UNIX EPOCH!"),
    }
}

 

posted @ 2024-02-27 14:51  Zhentiw  阅读(13)  评论(0)    收藏  举报