From c7c91173267632dbd4f082d1f27fcb1453be28a9 Mon Sep 17 00:00:00 2001 From: David Gauch Date: Mon, 6 Apr 2026 23:53:29 -0700 Subject: [PATCH] Add `const Default` impls for `LazyCell` and `LazyLock` --- library/core/src/cell/lazy.rs | 3 ++- library/std/src/sync/lazy_lock.rs | 3 ++- library/std/tests/sync/lazy_lock.rs | 9 +++++++++ library/std/tests/sync/lib.rs | 2 ++ 4 files changed, 15 insertions(+), 2 deletions(-) diff --git a/library/core/src/cell/lazy.rs b/library/core/src/cell/lazy.rs index ae559e599f48..9d350166c681 100644 --- a/library/core/src/cell/lazy.rs +++ b/library/core/src/cell/lazy.rs @@ -346,7 +346,8 @@ fn deref_mut(&mut self) -> &mut T { } #[stable(feature = "lazy_cell", since = "1.80.0")] -impl Default for LazyCell { +#[rustc_const_unstable(feature = "const_default", issue = "143894")] +impl const Default for LazyCell { /// Creates a new lazy value using `Default` as the initializing function. #[inline] fn default() -> LazyCell { diff --git a/library/std/src/sync/lazy_lock.rs b/library/std/src/sync/lazy_lock.rs index 9bdde0ae4a53..de1b9c391e8f 100644 --- a/library/std/src/sync/lazy_lock.rs +++ b/library/std/src/sync/lazy_lock.rs @@ -375,7 +375,8 @@ fn deref_mut(&mut self) -> &mut T { } #[stable(feature = "lazy_cell", since = "1.80.0")] -impl Default for LazyLock { +#[rustc_const_unstable(feature = "const_default", issue = "143894")] +impl const Default for LazyLock { /// Creates a new lazy value using `Default` as the initializing function. #[inline] fn default() -> LazyLock { diff --git a/library/std/tests/sync/lazy_lock.rs b/library/std/tests/sync/lazy_lock.rs index 68aeea834b4f..c549094dd138 100644 --- a/library/std/tests/sync/lazy_lock.rs +++ b/library/std/tests/sync/lazy_lock.rs @@ -33,6 +33,15 @@ fn default() -> Self { assert_eq!(CALLED.load(SeqCst), 1); } +#[test] +fn const_lazy_default() { + // using Box as it cannot be initialized in const contexts + const X: LazyLock> = <_>::default(); + const Y: LazyCell> = <_>::default(); + assert_eq!(**X, 0); + assert_eq!(**Y, 0); +} + #[test] #[cfg_attr(any(target_os = "emscripten", target_os = "wasi"), ignore)] // no threads fn sync_lazy_new() { diff --git a/library/std/tests/sync/lib.rs b/library/std/tests/sync/lib.rs index 32a7efde2a25..92c4c2f511be 100644 --- a/library/std/tests/sync/lib.rs +++ b/library/std/tests/sync/lib.rs @@ -1,3 +1,5 @@ +#![feature(const_default)] +#![feature(const_trait_impl)] #![feature(mapped_lock_guards)] #![feature(mpmc_channel)] #![feature(oneshot_channel)]