Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

OnceLock: Add note about drop and statics #118581

Merged
merged 1 commit into from
Dec 8, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 25 additions & 14 deletions library/std/src/sync/once_lock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,25 +17,36 @@ use crate::sync::Once;
/// ‘lazy static’ or ‘memoizing’):
///
/// ```
/// use std::collections::HashMap;
/// use std::sync::OnceLock;
///
/// fn hash_map() -> &'static HashMap<u32, char> {
/// static HASHMAP: OnceLock<HashMap<u32, char>> = OnceLock::new();
/// HASHMAP.get_or_init(|| {
/// let mut m = HashMap::new();
/// m.insert(0, 'a');
/// m.insert(1, 'b');
/// m.insert(2, 'c');
/// m
/// })
/// struct DeepThought {
/// answer: String,
/// }
///
/// // The `HashMap` is built, stored in the `OnceLock`, and returned.
/// let _ = hash_map();
/// impl DeepThought {
/// # fn great_question() -> String {
/// # "42".to_string()
/// # }
/// #
/// fn new() -> Self {
/// Self {
/// // M3 Ultra takes about 16 million years in --release config
/// answer: Self::great_question(),
/// }
/// }
/// }
///
/// fn computation() -> &'static DeepThought {
/// // n.b. static items do not call [`Drop`] on program termination, so if
/// // [`DeepThought`] impls Drop, that will not be used for this instance.
/// static COMPUTATION: OnceLock<DeepThought> = OnceLock::new();
/// COMPUTATION.get_or_init(|| DeepThought::new())
/// }
///
/// // The `HashMap` is retrieved from the `OnceLock` and returned.
/// let _ = hash_map();
/// // The `DeepThought` is built, stored in the `OnceLock`, and returned.
/// let _ = computation().answer;
/// // The `DeepThought` is retrieved from the `OnceLock` and returned.
/// let _ = computation().answer;
/// ```
///
/// Writing to a `OnceLock` from a separate thread:
Expand Down
Loading