In C++ variables with internal linkage are declared using static
. I tried the same in rust but getting compiler error related to thread safety. I need the variable to be mutable
static mut x: i32 = 5;
fn main() {
println!("{}", x);
x = 10;
println!("{}", x);
}
Error
error[E0133]: use of mutable static is unsafe and requires unsafe function or block
--> src/main.rs:4:20
|
4 | println!("{}", x);
| ^ use of mutable static
|
= note: mutable statics can be mutated by multiple threads: aliasing violations or data races will cause undefined behavior
= note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
error[E0133]: use of mutable static is unsafe and requires unsafe function or block
--> src/main.rs:6:5
|
6 | x = 10;
| ^^^^^^ use of mutable static
|
= note: mutable statics can be mutated by multiple threads: aliasing violations or data races will cause undefined behavior
error[E0133]: use of mutable static is unsafe and requires unsafe function or block
--> src/main.rs:7:20
|
7 | println!("{}", x);
| ^ use of mutable static
|
= note: mutable statics can be mutated by multiple threads: aliasing violations or data races will cause undefined behavior
= note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
For more information about this error, try `rustc --explain E0133`.
error: could not compile `playground` (bin "playground") due to 3 previous errors