static
变量保证只有一个实例,您可以引用它.const
变量没有这种保证,编译器可以有零个、一个或多个实例.
在您的情况下,代码相当于:
println!("{}", AtomicUsize::new(0).load(Ordering::SeqCst));
println!("{}", AtomicUsize::new(0).fetch_add(10, Ordering::SeqCst));
println!("{}", AtomicUsize::new(0).load(Ordering::SeqCst));
由于每个值都是被创建和丢弃的,因此不会将更改从一个值传播到另一个值.
在某些方面,你可以想到const
个变量,比如C或C++ #define
.从概念上来说,无论在哪里使用,都只粘贴值.
Clippy 0.0.211 has a lint for this case:
error: a const item should never be interior mutable
--> src/main.rs:3:1
|
3 | const SOME_VAR: AtomicUsize = AtomicUsize::new(0);
| -----^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| |
| help: make this a static item: `static`
|
= note: #[deny(declare_interior_mutable_const)] on by default
= help: for further information visit https://rust-lang-nursery.github.io/rust-clippy/v0.0.211/index.html#declare_interior_mutable_const
error: a const item with interior mutability should not be borrowed
--> src/main.rs:6:20
|
6 | println!("{}", SOME_VAR.load(Ordering::SeqCst));
| ^^^^^^^^
|
= note: #[deny(borrow_interior_mutable_const)] on by default
= help: assign this const to a local or static variable, and use the variable here
= help: for further information visit https://rust-lang-nursery.github.io/rust-clippy/v0.0.211/index.html#borrow_interior_mutable_const
在Java中,我可以使用final HashMap
是的,你可以很容易地用Java制作non-thread-safe HashMap
.Rust不想让创建可能导致内存不安全的代码变得容易.您需要使用适当的安全性来保护类型,比如Mutex
,或者如果you the programmer保证一个全局值只能由一个线程使用,则需要使用unsafe
代码.
另见: