Static mut variables in Rust2024

A few books have still examples for static mut variables. So I added one myself, telling that one should avoid them. But I think in last year the example was compiling, but now with Rust 2024 it fails in the playground, and I am unsure how I should modify the example and the text. The easiest way would be to just say that use of static mut is not longer permitted. Is that good enough? I discovered that a #![allow(static_mut_refs)] makes it compile in the playground. I will try to give a link to the playground example code, it is from section Variables and mutability - Rust for C-Programmers of the book.

In situations where no locally-reasoned abstraction is possible and you are therefore compelled still to reason globally about accesses to your static variable, you must now use raw pointers such as can be obtained via the &raw const or &raw mut operators. By first obtaining a raw pointer rather than directly taking a reference, (the safety requirements of) accesses through that pointer will be more familiar to unsafe developers and can be deferred until/limited to smaller regions of code.

So you could...

    unsafe {
        REQUEST_COUNTER += 1;
        println!("Requests processed (unsafe): {}", *&raw const REQUEST_COUNTER);
    }
1 Like

OK, it is discussed in the edition guide in Disallow references to static mut - The Rust Edition Guide

But I am still unsure how to modify the text. People might wonder why static mut was allowed for more than ten years, and no is forbidden. But well, I think a lot of alternatives are listed in the book, so perhaps I should just say that use of static mut is not any longer allowed.

The fact that many of the alternatives are only recently existing is why. Here's a relevant issue with tons of conversation. In terms of your book, I would say note especially the first dozen or so posts that hash out why UnsafeCell is safer than static mut (reentrancy, mere existence of aliasing references).

I'm on mobile now but as a passing thought: reading the (small) value into a temp and printing the temp could avoid creating a reference to the static place, unlike my snippet above.

1 Like