commit | 79338d44569ed2d24827a7e23b6d552f9847535b | [log] [tgz] |
---|---|---|
author | Treehugger Robot <treehugger-gerrit@google.com> | Wed Jun 15 22:28:14 2022 +0000 |
committer | Automerger Merge Worker <android-build-automerger-merge-worker@system.gserviceaccount.com> | Wed Jun 15 22:28:14 2022 +0000 |
tree | b733df8e10490ca94f221f649a725cd943c525c8 | |
parent | 2d09d3070de093d5f1d552c1e3fddaef4ef2f455 [diff] | |
parent | 2269dd2d06bcb212f07b580ab0c00daa72607231 [diff] |
Merge "Update TEST_MAPPING" am: 0113e08456 am: 1a69b4470c am: e5467b447a am: 2269dd2d06 Original change: https://android-review.googlesource.com/c/platform/external/rust/crates/once_cell/+/2125848 Change-Id: I9db5c7a074504a9cae48513339b6e60acd7067d5 Signed-off-by: Automerger Merge Worker <android-build-automerger-merge-worker@system.gserviceaccount.com>
once_cell
provides two new cell-like types, unsync::OnceCell
and sync::OnceCell
. OnceCell
might store arbitrary non-Copy
types, can be assigned to at most once and provide direct access to the stored contents. In a nutshell, API looks roughly like this:
impl OnceCell<T> { fn new() -> OnceCell<T> { ... } fn set(&self, value: T) -> Result<(), T> { ... } fn get(&self) -> Option<&T> { ... } }
Note that, like with RefCell
and Mutex
, the set
method requires only a shared reference. Because of the single assignment restriction get
can return an &T
instead of Ref<T>
or MutexGuard<T>
.
once_cell
also has a Lazy<T>
type, build on top of OnceCell
which provides the same API as the lazy_static!
macro, but without using any macros:
use std::{sync::Mutex, collections::HashMap}; use once_cell::sync::Lazy; static GLOBAL_DATA: Lazy<Mutex<HashMap<i32, String>>> = Lazy::new(|| { let mut m = HashMap::new(); m.insert(13, "Spica".to_string()); m.insert(74, "Hoyten".to_string()); Mutex::new(m) }); fn main() { println!("{:?}", GLOBAL_DATA.lock().unwrap()); }
More patterns and use-cases are in the docs!
The API of once_cell
is being proposed for inclusion in std
.