#RustQuiz: What is the output?

A. Compilation error
B. Prints 1
C. Panics at runtime
D. Prints 0

vote below
#rustlang

Vote here
A. Compilation error
38.7%
B. Prints 1
25.8%
C. Panics at runtime
6.5%
D. Prints 0
29%
Poll ended at .
The answer is
D. Prints 0
@AstraKernel Okay, I know what I thought the answer was going to be... and I was right on checking - but obviously for the wrong reasons, because recompiling with Ordering::SeqCst (or Ordering::Release and Ordering::Acquire for the load/stores specifically)... doesn't change the answer, which confuses me.
@AstraKernel Ah, yeah, I forgot that that's how rust deals with const - it seems that using atomics breaks the lint you get if you use "normal" ints...

@AstraKernel

Is it just because we're trying to change the value of a constant? (changing ATOMS to static works as I had expected)

It makes sense from the interfaces that it would compile, but if that really is the case then it seems like a (slightly obscure) footgun for sure.

@Visic

Yes clippy points out. But i misconfigured it in one of the editors. And I spent some time trying to figure out why the code didn't behave the way i expected. Finally found the culprit 😵

@AstraKernel

Ah, clippy, I was just trying it on the rust playground (with clippy off) and didn't think clippy would give me anything useful in this case 😅, pleasant surprise for sure. Thanks for posting this! I'm glad you were able to track down the problem, it's very subtle.

@AstraKernel Oooh, I know this one ^_^

The Ordering is a red herring. Every use of a const just copy-pastes the const expression into a new temporary. So ATOMS is replaced with [AtomicUsize::new(0); 4] in both lines, and accordingly the program prints 0.

The weird part is that mutating this temporary does not cause a compilation error - that's because AtomicUsize uses interior mutability, so AtomicUsize::store only requires a shared reference.

@AstraKernel i would've chopped my left hand it panicked, I would've made a great pirate.

@AstraKernel 26% of respondents think you can mutate a const

*glares at JavaScript*