hkBst
hkBst

Reputation: 3380

What is the scope of Rust's static variables?

In Rust global variables are declared with the static keyword. In C there is a difference between static variables (with translation unit scope) and non-static global variables (with truly global scope). Is it useful and possible to make this same distinction in Rust? If not, why not, and if so, how?

Upvotes: 0

Views: 2206

Answers (1)

Johann150
Johann150

Reputation: 785

Static variables have the same scoping rules as other things in a file. If you want it to be accessible from anywhere, you can make it pub, otherwise it will be private:

// 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;

Note that when you put code in another file, this will be a mod, i.e. you could have a file secret.rs and put the content of the secret module in that file etc.

This means that static variables are by default file specific like in C, with the exception of statics in the entry point file (e.g. A in the example above, the entry point file is usually main.rs or lib.rs), these are available in the whole crate. You can make them "truly global" by declaring them with pub.

Upvotes: 3

Related Questions