2

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?

4
  • Does this answer your question? How do I declare a static mutable variable without assignment? Commented Nov 1, 2019 at 22:47
  • 1
    You need to make the variable global. If you declare it within a function, it is accessible only by that function by design. Commented Nov 1, 2019 at 22:47
  • @SCappella It's not the same case, because what I'm looking for is using the same variable in two functions. Commented Nov 1, 2019 at 22:49
  • @mcarton Thanks for the tip. Using lazy_static helped out. Commented Nov 1, 2019 at 23:07

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

What he really wants is to share the static variable between two functions.
@mcarton Yes, that is the X of the XY, but I answered the actual question posted in the title, the Y. I added a clarification.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.