[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 @   Zhentiw  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2023-02-27 [Typescript] The partial Inference Problem
2019-02-27 [Functional Programming] Use Task/Async for Asynchronous Actions
2019-02-27 [Functional Programming] Working with two functors(Applicative Functors)-- Part2 --liftAN
2018-02-27 [CSS3] Create Dynamic Styles with CSS Variables
2017-02-27 [Flow] The Fundamentals of Flow
2017-02-27 [Angular] Some performance tips
2017-02-27 [Ramda] Rewrite if..else with Ramda ifElse
点击右上角即可分享
微信分享提示