#懒加载 #初始化 #缓存

sloth

提供用于懒初始化的泛型包装结构体

5个版本

0.2.0 2019年9月3日
0.1.3 2019年9月1日
0.1.2 2019年9月1日
0.1.1 2019年8月31日
0.1.0 2019年8月31日

#222缓存

Download history 1542/week @ 2024-01-29 670/week @ 2024-02-05 3/week @ 2024-02-12 15/week @ 2024-02-19 88/week @ 2024-02-26 63/week @ 2024-03-04 45/week @ 2024-03-11 31/week @ 2024-03-18 21/week @ 2024-03-25 36/week @ 2024-04-01 56/week @ 2024-04-08 28/week @ 2024-04-15 4/week @ 2024-04-22 120/week @ 2024-04-29 41/week @ 2024-05-06 28/week @ 2024-05-13

每月194次下载

MIT/Apache

23KB
384

docs.rs Build Status

sloth

此crate提供了一个类似于指针的泛型结构体 Lazy<T, Eval> 用于懒加载值。它可以用于计算成本高的值,以确保评估逻辑只运行一次,并且在需要时才运行。

例如

use sloth::Lazy;

fn get_expensive_string() -> String {
    // do something expensive here to obtain the result,
    // such as read and process file contents
    String::from("some expensive string we got from a file or something")
}

fn get_expensive_number() -> i32 {
    // do something expensive here to calculate the result,
    // such as build a supercomputer and wait 7.5 million years
    42
}

let lazy_string = Lazy::new(get_expensive_string);
let lazy_number = Lazy::new(get_expensive_number);

//...
let must_use_string = true;
//...

if must_use_string {
    println!("Expensive string is: {}", *lazy_string);
    println!("It has length: {}", lazy_string.len());

    // get_expensive_string() has been called only once,
    // get_expensive_number() has not been called
} else {
    println!("Expensive number is: {}", *lazy_number);
    println!("Its square is {}", lazy_number.pow(2));

    // get_expensive_string() has not been called,
    // get_expensive_number() has been called only once
}

可变 Lazy 的评估值可以被修改

use sloth::Lazy;

let mut lazy_vec = Lazy::new(|| vec![2, -5, 6, 0]);

lazy_vec.retain(|n| *n > 0);

assert_eq!(*lazy_vec, vec![2, 6]);

Lazy 可以通过 unwrap() 方法被消费并转换为其实际值

use sloth::Lazy;

let lazy_value = Lazy::new(|| "moo");

let output = String::from("a cow goes ") + lazy_value.unwrap();

无运行时依赖