Search code examples
ruststatic-variablesvariable-declaration

How is it possible to share a static variable between functions?


I'm trying to define a static variable within a function f0 and re-use it within another function f1.

fn f0() {
    static v: i32 = 10;
}

fn f1() {
    static v: i32; // the compiler reports a syntax error for this statement
}

However, because it wasn't assigned to any value in the second function, the compiler reported an error saying:

expected one of !, (, +, ::, <, or =, found ;

I'm using nightly Rust toolchain: rustc 1.40.0-nightly.

This sounds little odd, since declaring a static variable doesn't require value assignment by nature.

What's supposed to cause the problem?


Solution

  • You cannot declare static variables that are not initialized, because the Rust compiler assumes that all variables are initialized.

    If you really want to do it, you will want to use std::mem::MaybeUninit.

    However, even if you did that, it wouldn't solve your original issue (sharing a static variable between functions). Each static in your example is independent of each other.

    Therefore, you will need to make a global static variable.