1

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?

user6039980
  • 3,108
  • 8
  • 31
  • 57
  • Does this answer your question? [How do I declare a static mutable variable without assignment?](https://stackoverflow.com/questions/30145814/how-do-i-declare-a-static-mutable-variable-without-assignment) – SCappella Nov 01 '19 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. – mcarton Nov 01 '19 at 22:47
  • @SCappella It's not the same case, because what I'm looking for is using the same variable in two functions. – user6039980 Nov 01 '19 at 22:49
  • @mcarton Thanks for the tip. Using lazy_static helped out. – user6039980 Nov 01 '19 at 23:07

1 Answers1

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.

Acorn
  • 24,970
  • 5
  • 40
  • 69
  • What he really wants is to share the static variable between two functions. – mcarton Nov 01 '19 at 22:47
  • 1
    @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. – Acorn Nov 01 '19 at 22:48