Rollup merge of #154929 - davidgauch:const-default-lazy, r=jhpratt

Add `const Default` impls for `LazyCell` and `LazyLock`

Follow up to these commits by @estebank https://github.com/rust-lang/rust/pull/134628 and https://github.com/rust-lang/rust/pull/151190.
Tracking issue https://github.com/rust-lang/rust/issues/143894.

cc @fmease @fee1-dead @oli-obk

This enables `static L: LazyLock<D> = Default::default()`  for any type `D: Default` which is safe as `D::default()` is only evaluated at runtime.
This commit is contained in:
Jonathan Brouwer
2026-04-13 20:20:02 +02:00
committed by GitHub
4 changed files with 15 additions and 2 deletions
+2 -1
View File
@@ -375,7 +375,8 @@ fn deref_mut(&mut self) -> &mut T {
}
#[stable(feature = "lazy_cell", since = "1.80.0")]
impl<T: Default> Default for LazyLock<T> {
#[rustc_const_unstable(feature = "const_default", issue = "143894")]
impl<T: Default> const Default for LazyLock<T> {
/// Creates a new lazy value using `Default` as the initializing function.
#[inline]
fn default() -> LazyLock<T> {
+9
View File
@@ -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<Box<u8>> = <_>::default();
const Y: LazyCell<Box<u8>> = <_>::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() {
+2
View File
@@ -1,3 +1,5 @@
#![feature(const_default)]
#![feature(const_trait_impl)]
#![feature(mapped_lock_guards)]
#![feature(mpmc_channel)]
#![feature(oneshot_channel)]