Const ArcSwapOption doesn't update values
Bauxitedev opened this issue · comments
Hello, I am writing a program that uses a global ArcSwapOption<String>
, but it seems the values I put into it aren't updated.
I call store
to put something into it, but calling load
afterwards still returns None
.
A quick reproduction example: (you can run it directly with cargo script
)
// cargo-deps: arc-swap="=1.5.0"
extern crate arc_swap;
use arc_swap::*;
use std::sync::Arc;
pub const SWAP: ArcSwapOption<String> = ArcSwapOption::const_empty();
fn main() {
SWAP.store(Some(Arc::new("test".to_owned())));
std::thread::sleep_ms(1000);
dbg!(SWAP.load());
dbg!(SWAP.load_full());
}
The program outputs...
[arc_swap_test.rs:12] SWAP.load() = None
[arc_swap_test.rs:13] SWAP.load_full() = None
...even though I clearly put the string test
into the ArcSwapOption
.
Am I doing something wrong here? Or is this a bug?
This is actually a weirdness of how const
works, const
is a compile time „bit pattern“ that can be copied any time it is used even though the type is not Copy. Therefore, it creates a new ArcSwapOption
at the first load, stores it there and throws it away. Then it takes another (empty, original) copy of the const to load from. I'm not sure if I can prevent this trap from inside the crate in some way, I think (I'm not looking for it right now) it's even mentioned in the documentation somewhere to watch out for it.
Anyway, the solution is to use static SWAP: ...
instead of const SWAP: ...
Ah I see, static
fixed it. Thanks for the quick response.