Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to declare 2 static mutable variables depending on each other?

Tags:

rust

I am trying to declare two static mutable variables but I have a error:

static mut I: i64 = 5;
static mut J: i64 = I + 3;

fn main() {
    unsafe {
        println!("I: {}, J: {}", I, J);
    }
}

Error:

error[E0133]: use of mutable static is unsafe and requires unsafe function or block
 --> src/main.rs:2:21
  |
2 | static mut J: i64 = I + 3;
  |                     ^ use of mutable static
  |
  = note: mutable statics can be mutated by multiple threads: aliasing violations or data races will cause undefined behavior

Is it impossible? I also tried to put an unsafe block on the declaration but it seems to be incorrect grammar:

static mut I: i64 = 5;

unsafe {
    static mut J: i64 = I + 3;
}
like image 378
Victor Polevoy Avatar asked Nov 19 '18 14:11

Victor Polevoy


People also ask

Are static variables mutable?

Static variables can be mutable.

Can static be mutable?

Mutable statics are still very useful, however. They can be used with C libraries and can also be bound from C libraries in an extern block. Mutable statics have the same restrictions as normal statics, except that the type does not have to implement the Sync trait.


1 Answers

Yes it is.

In your case, just remove mut, because static globals are safe to access, because they cannot be changed and therefore do not suffer from all the bad attributes, like unsynchronized access.

static I: i64 = 5;
static J: i64 = I + 3;

fn main() {
    println!("I: {}, J: {}", I, J);
}

If you want them to be mutable, you can use unsafe where you access the unsafe variable (in this case I).

static mut I: i64 = 5;
static mut J: i64 = unsafe { I } + 3;

fn main() {
    unsafe {
        println!("I: {}, J: {}", I, J);
    }
}
like image 188
hellow Avatar answered Nov 15 '22 11:11

hellow