The code is copied from Listing 19-10 of The Rust Programming Language. It's meant to illustrate the use of mutable static variables, but that's not my concern here. Even though this may be fairly labelled as a "toy example", in a book introducing Rust, it raises what I think are serious issues.
All of the code of add_to_count
is in an unsafe
block. What good does this do, as opposed to making the function itself unsafe
? As is, the signature of the function gives no clue that it is - in essence if not in Rust parlance - unsafe. I wonder why the compiler even allows this. The "benefit" is that, as can be seen below, the function can be called outside of an unsafe
block. Why would an introductory text on Rust show how to circumvent a safe programming practice?
static mut COUNTER: u32 = 0;
fn add_to_count(inc: u32) {
unsafe {
COUNTER += inc;
}
}
fn main() {
add_to_count(3);
unsafe {
println!("COUNTER: {}", COUNTER);
}
}
If a function is marked as unsafe
it means that the caller is responsible for upholding some number of conditions, otherwise undefined behavior may be introduced.
If a function is not marked as unsafe
but contains unsafe code, then it means that the function is guaranteeing that no choice of parameters will cause unsafe behavior. In practice this often means the function will check some conditions and panic if the conditions aren't met.
By not marking the function as unsafe
in your example, the author is asserting that nothing can go wrong by mutating a static mut u32
by some caller-defined amount.
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