rust - 是否可以声明 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;
}
解决方案
是的。
在您的情况下,只需 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);
}
}
推荐阅读
- angular - 具有多个嵌套组件的 Angular 2-way 绑定
- javascript - 如何同时验证多个输入字段
- c# - 如何使autofac实时解析带参数的构造函数?
- android - 添加带有导航抽屉的启动屏幕活动不起作用
- c - GStreamer GstVideoTestSrcPattern 枚举 - 它在哪里?
- c# - Botframework v4:发送打字指示
- sql - 允许登录运行存储过程而不能从表中选择
- python - 增加对 Python 参数变量的理解
- linux - 如何在linux中使用一个命令的输出作为另一个命令
- unity3d - 如何通过统一arcore录制视频?