Rust 的静态变量的范围是什么?

What is the scope of Rust's static variables?

In Rust global variables are declared with the static keyword. 在 C 中,静态变量(具有翻译单元作用域)和非静态全局变量(具有真正的全局作用域)是有区别的。在 Rust 中做出同样的区分是否有用且可能?如果不是,为什么不,如果是,怎么做?

静态变量与文件中的其他内容具有相同的范围规则。如果你想让它可以从任何地方访问,你可以把它设为pub,否则它将是私有的:

// accessible from inside the crate
static A: f32 = 3.141;

mod secret {
    // accessible from inside this module
    static B: u8 = 42;
}

mod not_secret {
    // accessible from inside the crate
    pub static C: u8 = 69;
}

pub mod public {
    // accessible from anywhere
    pub static D: u16 = 420;
}

// accessible from anywhere
pub static E: u16 = 1337;

请注意,当您将代码放入另一个文件时,这将是一个 mod,即您可以拥有一个文件 secret.rs 并将 secret 模块的内容放入该文件文件等

这意味着静态变量在默认情况下是特定于文件的,就像在 C 中一样,除了入口点文件中的 statics(例如上面示例中的 A,入口点文件通常是 main.rslib.rs),这些在整个板条箱中可用。您可以通过使用 pub.

声明它们来使它们“真正全球化”