pub struct User {
pub name: String,
pub age: u32,
}
use std::sync::{Arc, OnceLock};
use tokio::sync::Mutex;
pub const PROCESSES: OnceLock<Arc<Mutex<Vec<User>>>> = OnceLock::new();
fn main() {
PROCESSES.get_or_init(|| Arc::new(Mutex::new(vec![])));
let v = PROCESSES.get().unwrap();
}
I remember I often use it this way, but today’s result made me question my whole existence.
Or perhaps only today did I realize it was wrong??
The result:
thread 'main' panicked at src/main.rs:16:29:
called Option::unwrap()
on a None
value
note: run with RUST_BACKTRACE=1
environment variable to display a backtrace
You must use a static
item, not a const
item. Only static
guarantees a single shared memory location.
3 Likes
I'm so foolish, I didn't even notice. Thank you for your help. Neither ChatGPT nor DeepSeek pointed out this mistake...
LLMs arent typically good at Rust at all beyond the basics.
3 Likes
Note that clippy would have warned you about this:
warning: a `const` item should not be interior mutable
--> src/main.rs:9:1
|
9 | pub const PROCESSES: OnceLock<Arc<Mutex<Vec<User>>>> = OnceLock::new();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= help: consider making this a static item
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#declare_interior_mutable_const
= note: `#[warn(clippy::declare_interior_mutable_const)]` on by default
warning: a `const` item with interior mutability should not be borrowed
--> src/main.rs:12:5
|
12 | PROCESSES.get_or_init(|| Arc::new(Mutex::new(vec![])));
| ^^^^^^^^^
|
= help: assign this const to a local or static variable, and use the variable here
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#borrow_interior_mutable_const
= note: `#[warn(clippy::borrow_interior_mutable_const)]` on by default
warning: a `const` item with interior mutability should not be borrowed
--> src/main.rs:14:13
|
14 | let v = PROCESSES.get().unwrap();
| ^^^^^^^^^
|
= help: assign this const to a local or static variable, and use the variable here
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#borrow_interior_mutable_const
6 Likes
Very good advice, thank you.