Modules Group Code Behind Paths

Group related types in an inline module, expose only what the API needs through pub and pub(crate), and reach it with use paths.

RustConfig Management

Code

rustsnippet
29 lines
mod config {
    // 模块内默认私有:pub 才对外可见
    pub struct Settings {
        pub(crate) timeout_secs: u32, // crate 内可见
        retries: u32,                 // 仅 config 模块内可见
    }

    impl Settings {
        pub fn new(timeout_secs: u32) -> Self {
            Self { timeout_secs, retries: 3 }
        }
        pub fn retries(&self) -> u32 {
            self.retries
        }
    }

    pub fn defaults() -> Settings {
        Settings::new(30)
    }
}

// use 路径把嵌套模块的名字引入作用域
use config::Settings;

fn main() {
    let settings: Settings = config::defaults();
    // 外部只能走 pub 面:pub(crate) 字段同 crate 可读,私有字段必须经方法
    println!("timeout: {}s retries: {}", settings.timeout_secs, settings.retries());
}

How it works

Count the functions new, retries, defaults and main as the entire surface area of Modules Group Code Behind Paths.

What to watch for

  • Plan for an install step: config::Settings is a real dependency, resolved by the package manager.

Putting it to use

The main signature reads fn new(timeout_secs: u32) -> Self

The demo output is labeled (timeout:), so every printed line maps back to its originating operation.

Treat main as the orchestrator calling defaults and retries in a fixed order.

Core lines

pub fn new(timeout_secs: u32) -> Self {
Self { timeout_secs, retries: 3 }
}
pub fn defaults() -> Settings {
Settings::new(30)
}
pub fn retries(&self) -> u32 {
self.retries
}

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
Yes: `config::Settings` must be present in the project or the import fails at load time.