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.

RustSecurity Boundaries

Code

rustsnippet
23 lines
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

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.