Repository navigation
More methods to OnceCell #77
Copy link
Copy link
Closed
Labels
enhancementNew feature or requestNew feature or requestgood first issueGood for newcomersGood for newcomershelp wantedExtra attention is neededExtra attention is needed
Description
Activity
- addedenhancementNew feature or requestNew feature or requesthelp wantedExtra attention is neededExtra attention is neededgood first issueGood for newcomersGood for newcomers
on Nov 25, 2025 I'm wondering if it's worth implementing a
get_mut_or_init. This method should accept a mutable reference so that it cannot be called concurrently.A typical use case for modifying a mutable reference is calling
get_or_initon anOnceCellwhose value is something likeArc<Mutex<T>>so that it can be modified concurrently.#[test] fn multi_init_mut() { let rt = tokio::runtime::Builder::new_multi_thread() .worker_threads(4) .enable_time() .build() .unwrap(); static CELL: OnceCell<AtomicUsize> = OnceCell::new(); rt.block_on(async { const N: usize = 100; let mut handles = vec![]; for i in 0..N { handles.push(rt.spawn(async move { let result = CELL .get_or_init(move || async move { AtomicUsize::new(1000 + i) }) .await; result.fetch_add(1, Ordering::Relaxed); tokio::time::sleep(Duration::from_millis(100)).await; result.load(Ordering::Relaxed) })); } let mut values = vec![]; for handle in handles { values.push(handle.await.unwrap()); } let value = CELL.get().unwrap().load(Ordering::Relaxed); assert!( value >= 1000 + N && value < 1000 + N + N, "final value: {}", value ); for v in values { assert_eq!(v, value); } }); }
You can see the linked issue.
While async primitives can be used to share cross threads, our OnceCell can be used as an analogy to std OnceLock while its pass-in function is an async fn.
Thus, this can be used as a cell that initialized only once and need not shared among threads.
Okay, it makes sense
Metadata
Metadata
Assignees
Labels
enhancementNew feature or requestNew feature or requestgood first issueGood for newcomersGood for newcomershelp wantedExtra attention is neededExtra attention is needed
get_or_try_initget_mutget_mut_or_initget_mut_or_try_initsettry_inserttakeYou can refer to:
Also, it's possible to add a
LazyCellprimitive that has a pre-configured initializer (closure).