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);
}
}