Reputation: 16685
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;
}
Upvotes: 5
Views: 1082
Reputation: 13420
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);
}
}
Upvotes: 9