5

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;
}
3
  • 1
    Not sure about your usecase, but this is a bad idea to do so, unless you really know what you do. Commented Nov 19, 2018 at 14:51
  • 1
    Global, static, mutable variables are pure evil! Use lazy_static!, RefCell or a Mutex, if you really have to, but I would avoid them at all cost! Commented Nov 19, 2018 at 14:57
  • @hellow Oh, guys, of course I know that, I was just curious whether I can do so or not, because, you know, when I saw that I could not do this even with unsafe block, I was stuck. I haven't had a real use case for this by now, but I wanted to know whether it was possible in general or not. Commented Nov 20, 2018 at 7:55

1 Answer 1

9

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.