Skip to content

Commit

Permalink
Add a Lazy::get function, similar to OnceCell::get
Browse files Browse the repository at this point in the history
  • Loading branch information
glandium committed Jul 4, 2022
1 parent 2be67cc commit 61e27f9
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -741,6 +741,23 @@ pub mod unsync {
None => panic!("Lazy instance has previously been poisoned"),
})
}

/// Gets the reference to the result of this lazy value if
/// it was initialized, otherwise returns `None`.
///
/// # Example
/// ```
/// use once_cell::unsync::Lazy;
///
/// let lazy = Lazy::new(|| 92);
///
/// assert_eq!(Lazy::get(&lazy), None);
/// assert_eq!(&*lazy, &92);
/// assert_eq!(Lazy::get(&lazy), Some(&92));
/// ```
pub fn get(this: &Lazy<T, F>) -> Option<&T> {
this.cell.get()
}
}

impl<T, F: FnOnce() -> T> Deref for Lazy<T, F> {
Expand Down Expand Up @@ -1214,6 +1231,23 @@ pub mod sync {
None => panic!("Lazy instance has previously been poisoned"),
})
}

/// Gets the reference to the result of this lazy value if
/// it was initialized, otherwise returns `None`.
///
/// # Example
/// ```
/// use once_cell::sync::Lazy;
///
/// let lazy = Lazy::new(|| 92);
///
/// assert_eq!(Lazy::get(&lazy), None);
/// assert_eq!(&*lazy, &92);
/// assert_eq!(Lazy::get(&lazy), Some(&92));
/// ```
pub fn get(this: &Lazy<T, F>) -> Option<&T> {
this.cell.get()
}
}

impl<T, F: FnOnce() -> T> Deref for Lazy<T, F> {
Expand Down

0 comments on commit 61e27f9

Please sign in to comment.