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.
Code
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::Settingsis 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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.