Module Visibility With Pub And Crate
Control what a module exposes with pub and pub(crate), keeping internal helpers invisible while the public surface stays minimal.
Code
mod ledger {
// pub(crate): crate 内可见,对外不可见
pub(crate) fn audit_trail() -> String {
String::from("audit-ok")
}
// pub:完全公开
pub fn balance() -> i32 {
// 内部助手只能在模块内引用
compute() + 0
}
// 私有:模块外不可见
fn compute() -> i32 {
42
}
}
fn main() {
println!("balance: {}", ledger::balance());
// ledger::compute(); // 私有:编译错误
println!("audit: {}", ledger::audit_trail());
}How the snippet works
The part worth importing is the functions audit_trail, balance, compute and main — everything else is wiring.
Applying it
The primary signature, spelled out, is fn audit_trail() -> String
The demo output is labeled (balance:, audit:), so each printed line points back to the operation that produced it.
main is the driver: it invokes balance, compute and audit_trail before returning.
Statements that matter
pub(crate) fn audit_trail() -> String {
String::from("audit-ok")
}
pub fn balance() -> i32 {
// 内部助手只能在模块内引用
compute() + 0
}
fn compute() -> i32 {
42
}
Interactive Tools for This Topic
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
FAQ
- What does Module Visibility With Pub And Crate print when run?
- No setup needed: run the file and look for labeled lines like `balance:`, `audit:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.