是否可以声明两个相互依赖的静态可变变量?

时间:2018-11-19 14:43:01

标签: rust

我正在尝试声明两个静态可变变量,但是我有一个error

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

这不可能吗?我也尝试过put an unsafe block on the declaration,但语法似乎不正确:

static mut I: i64 = 5;

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

1 个答案:

答案 0 :(得分:8)

是的。

在您的情况下,只需删除 var Ycompensator = 0; function circle (name, setTemp, temp){ c=document.getElementById(name); var ctx=c.getContext("2d"); c.width = 200; c.height = 300; ctx.fillStyle = "gray"; ctx.fillRect(0, 0, c.width, c.height); ctx.beginPath(); ctx.arc(100,170,5,0,2*Math.PI); ctx.fillStyle = 'black'; ctx.fill(); } circle ('den'); circle ('wc'); var den=document.getElementById('den'); den.addEventListener('mousedown',denClicked, false); function denClicked(event){ c=document.getElementById('den'); var rect = c.getBoundingClientRect() var x = event.pageX - rect.left; var y = event.pageY - rect.top; console.log('x: ' + x + ' y: ' + y); } var wc=document.getElementById('wc'); wc.addEventListener('mousedown',wcClicked, false); function wcClicked(event){ var w = window.innerWidth; if (w < 768){ Ycompensator = 324; } c=document.getElementById('wc'); var rect = c.getBoundingClientRect() var x = event.pageX - rect.left; var y = event.pageY - Ycompensator; console.log('x: ' + x + ' y: ' + y); } ,因为可以安全地访问静态全局变量,因为它们无法更改,因此不会遭受所有不良属性(例如非同步访问)的困扰。

mut

如果希望它们是可变的,则可以在访问不安全变量(在这种情况下为static I: i64 = 5; static J: i64 = I + 3; fn main() { println!("I: {}, J: {}", I, J); } )中使用unsafe

I