Crate lazy_into

Crate lazy_into 

Source
Expand description

§Lazy Into

Lazy conversion from one type to another in Rust.

Converts from types T to U with a mapping function that is only called the first time it’s needed.

§Usage

This is useful when you have an expensive conversion that may not even be needed.


For example, if you have a CLI app that parses deep into JSON data that the user can see by typing “data”, a LazyInto could be useful.

If the user never says “data”, the search is not needed.

If the user says “data” multiple times, the search is only needed once.

A regular LazyCell can not take input parameters.

§Example Usage

fn main() {
    use lazy_into::LazyInto;

    let a = LazyInto::new(42, |n| n as f64 * 2.0);
    let b = LazyInto::new(21, TryInto::try_into);
    let mut c = LazyInto::new(-1, |n| n.to_string());

    assert_eq!(a.get(), &84.0);
    assert_eq!(*a, 84.0);
    assert_eq!(*b, Ok(21u32));

    assert_eq!(*c, "-1");
    c.get_mut().push_str("2345");
    assert_eq!(*c, "-12345");
}

Structs§

LazyInto
A lazy conversion from type T to U that is only done via the given mapping function/closure the first time the output is needed.

Type Aliases§

LazyIntoFn
An alias for LazyInto that uses fn(T) -> U so it doesn’t have to be typed out.