[][src]Struct sloth::Lazy

pub struct Lazy<T, Eval> where
    Eval: FnOnce() -> T, 
{ /* fields omitted */ }

Represents a value of type T, lazily evaluated using a parameterless function or a closure (FnOnce() -> T) passed to Lazy::new().

The value within may be referenced using value_ref() or value_mut() methods. For types implementing Copy, a copy of the contained value may be obtained using value().

The evaluator function will not be called more than once. If none of value(), value_ref() and value_mut() methods are used, the evaluator function will never be called at all.

Examples

Lazily converting a string to upper case:

use sloth::Lazy;
 
let some_str = "the quick brown fox jumps over the lazy dog";
let lazy_upper_str = Lazy::new(|| some_str.to_uppercase());
 
assert_eq!(
    *lazy_upper_str.value_ref(),
    "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG"
);

Regardless of how many times the value is accessed, the evaluator function is only called once:

use sloth::Lazy;
 
let mut evaluator_called_times = 0;
 
let lazy_value = Lazy::new(|| {
    evaluator_called_times += 1;
    25
});
 
assert_eq!(lazy_value.value(), 25);
 
let another_value = lazy_value.value() + lazy_value.value();
 
assert_eq!(evaluator_called_times, 1);

Methods

impl<T, Eval> Lazy<T, Eval> where
    Eval: FnOnce() -> T, 
[src]

pub fn new(evaluator: Eval) -> Self[src]

pub fn value_ref(&self) -> Ref<T>[src]

pub fn value_mut(&mut self) -> RefMut<T>[src]

impl<T, Eval> Lazy<T, Eval> where
    T: Copy,
    Eval: FnOnce() -> T, 
[src]

pub fn value(&self) -> T[src]

Auto Trait Implementations

impl<T, Eval> Send for Lazy<T, Eval> where
    Eval: Send,
    T: Send

impl<T, Eval> Unpin for Lazy<T, Eval> where
    Eval: Unpin,
    T: Unpin

impl<T, Eval> !Sync for Lazy<T, Eval>

impl<T, Eval> UnwindSafe for Lazy<T, Eval> where
    Eval: UnwindSafe,
    T: UnwindSafe

impl<T, Eval> !RefUnwindSafe for Lazy<T, Eval>

Blanket Implementations

impl<T> From<T> for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> Any for T where
    T: 'static + ?Sized
[src]