0

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
Harry
  • 2,177
  • 1
  • 19
  • 33
  • Rust's `static` has a different meaning than C++'s and isn't related to linkage. In fact, it's not really meaningful to talk about linkage at all in Rust unless you're working with FFIs, which this code is not. Is what you're trying to do creating a mutable global variable? – Brian61354270 Jun 30 '23 at 16:42
  • Yeah, I agree that in Rust-land this doesn't really relate to linking. Does this help? https://doc.rust-lang.org/reference/items/static-items.html#mutable-statics – isaactfa Jun 30 '23 at 16:43
  • If you care about the "not usable by code outside this file" part of internal linkage, then that maps to [visibility](https://doc.rust-lang.org/reference/visibility-and-privacy.html) in Rust. – Brian61354270 Jun 30 '23 at 16:45
  • @Brian61354270 that's what I am looking for. I tried to declare an `i32` inside `mod M`, but still getting compilation error – Harry Jun 30 '23 at 17:41

0 Answers0