首页 > 解决方案 > 是否可以声明 2 个相互依赖的静态可变变量?

问题描述

我正在尝试声明两个静态可变变量,但出现错误

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

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

错误:

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

这是不可能的吗?我还尝试在声明中放置一个unsafe块,但它似乎是不正确的语法:

static mut I: i64 = 5;

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

标签: rust

解决方案


是的。

在您的情况下,只需 remove mut,因为静态全局变量可以安全访问,因为它们无法更改,因此不会受到所有不良属性的影响,例如非同步访问。

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

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

如果您希望它们是可变的,您可以使用unsafe访问不安全变量的位置(在这种情况下I)。

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

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

推荐阅读