Rollup merge of #126509 - workingjubilee:gently-discourage-doing-things-once, r=jhpratt

std: suggest OnceLock over Once

It was noted in https://github.com/rust-lang/rust/issues/125615#issuecomment-2149590818 that Once is not necessary in most cases and should be discouraged. Once is really just an implementation detail of OnceLock that others can use if they want. Suggest they use OnceLock instead.
This commit is contained in:
Matthias Krüger 2024-06-15 10:56:44 +02:00 committed by GitHub
commit 83cbceac0f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 14 additions and 4 deletions

View File

@ -133,7 +133,8 @@
//! - [`Mutex`]: Mutual Exclusion mechanism, which ensures that at //! - [`Mutex`]: Mutual Exclusion mechanism, which ensures that at
//! most one thread at a time is able to access some data. //! most one thread at a time is able to access some data.
//! //!
//! - [`Once`]: Used for a thread-safe, one-time global initialization routine //! - [`Once`]: Used for a thread-safe, one-time global initialization routine.
//! Mostly useful for implementing other types like `OnceLock`.
//! //!
//! - [`OnceLock`]: Used for thread-safe, one-time initialization of a //! - [`OnceLock`]: Used for thread-safe, one-time initialization of a
//! variable, with potentially different initializers based on the caller. //! variable, with potentially different initializers based on the caller.

View File

@ -10,9 +10,15 @@
use crate::panic::{RefUnwindSafe, UnwindSafe}; use crate::panic::{RefUnwindSafe, UnwindSafe};
use crate::sys::sync as sys; use crate::sys::sync as sys;
/// A synchronization primitive which can be used to run a one-time global /// A low-level synchronization primitive for one-time global execution.
/// initialization. Useful for one-time initialization for FFI or related ///
/// functionality. This type can only be constructed with [`Once::new()`]. /// Previously this was the only "execute once" synchronization in `std`.
/// Other libraries implemented novel synchronizing types with `Once`, like
/// [`OnceLock<T>`] or [`LazyLock<T, F>`], before those were added to `std`.
/// `OnceLock<T>` in particular supersedes `Once` in functionality and should
/// be preferred for the common case where the `Once` is associated with data.
///
/// This type can only be constructed with [`Once::new()`].
/// ///
/// # Examples /// # Examples
/// ///
@ -25,6 +31,9 @@
/// // run initialization here /// // run initialization here
/// }); /// });
/// ``` /// ```
///
/// [`OnceLock<T>`]: crate::sync::OnceLock
/// [`LazyLock<T, F>`]: crate::sync::LazyLock
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
pub struct Once { pub struct Once {
inner: sys::Once, inner: sys::Once,