Skip to content

More inference-friendly API for lazy #103718

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

Merged
merged 1 commit into from
Dec 28, 2022
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
4 changes: 1 addition & 3 deletions library/core/src/cell/lazy.rs
Original file line number Diff line number Diff line change
@@ -31,7 +31,7 @@ pub struct LazyCell<T, F = fn() -> T> {
init: Cell<Option<F>>,
}

impl<T, F> LazyCell<T, F> {
impl<T, F: FnOnce() -> T> LazyCell<T, F> {
/// Creates a new lazy value with the given initializing function.
///
/// # Examples
@@ -51,9 +51,7 @@ impl<T, F> LazyCell<T, F> {
pub const fn new(init: F) -> LazyCell<T, F> {
LazyCell { cell: OnceCell::new(), init: Cell::new(Some(init)) }
}
}

impl<T, F: FnOnce() -> T> LazyCell<T, F> {
/// Forces the evaluation of this lazy value and returns a reference to
/// the result.
///
6 changes: 6 additions & 0 deletions library/core/tests/lazy.rs
Original file line number Diff line number Diff line change
@@ -106,6 +106,12 @@ fn lazy_new() {
assert_eq!(called.get(), 1);
}

// Check that we can infer `T` from closure's type.
#[test]
fn lazy_type_inference() {
let _ = LazyCell::new(|| ());
}

#[test]
fn aliasing_in_get() {
let x = OnceCell::new();
5 changes: 1 addition & 4 deletions library/std/src/sync/lazy_lock.rs
Original file line number Diff line number Diff line change
@@ -44,17 +44,14 @@ pub struct LazyLock<T, F = fn() -> T> {
cell: OnceLock<T>,
init: Cell<Option<F>>,
}

impl<T, F> LazyLock<T, F> {
impl<T, F: FnOnce() -> T> LazyLock<T, F> {
/// Creates a new lazy value with the given initializing
/// function.
#[unstable(feature = "once_cell", issue = "74465")]
pub const fn new(f: F) -> LazyLock<T, F> {
LazyLock { cell: OnceLock::new(), init: Cell::new(Some(f)) }
}
}

impl<T, F: FnOnce() -> T> LazyLock<T, F> {
/// Forces the evaluation of this lazy value and
/// returns a reference to result. This is equivalent
/// to the `Deref` impl, but is explicit.
6 changes: 6 additions & 0 deletions library/std/src/sync/lazy_lock/tests.rs
Original file line number Diff line number Diff line change
@@ -136,6 +136,12 @@ fn sync_lazy_poisoning() {
}
}

// Check that we can infer `T` from closure's type.
#[test]
fn lazy_type_inference() {
let _ = LazyCell::new(|| ());
}

#[test]
fn is_sync_send() {
fn assert_traits<T: Send + Sync>() {}