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;
}
Static variables can be mutable.
Mutable statics are still very useful, however. They can be used with C libraries and can also be bound from C libraries in an extern block. Mutable statics have the same restrictions as normal statics, except that the type does not have to implement the Sync trait.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With