< 返回版块

liangyongrui 发表于 2021-02-19 12:15

lazy_static 的异步版本

用法非常的简单

dependencies

async_static = "0.1"
once_cell = "1"
# Only used in the current example
tokio = { version = "1", features = ["full"] }

src

use async_static::async_static;
use tokio::time::sleep;

async fn get_num() -> i32 {
    println!("hello world");
    sleep(Duration::from_millis(100)).await;
    123
}

async_static! {
    static ref FOO:i32 = get_num().await;
}

/// run print
/// ```
/// hello world
/// The result of the first call: 123
/// The result of the second call: 123
/// ```
#[tokio::test]
async fn test() {
    // The first call, print hello world
    let n = FOO.await;
    println!("The result of the first call: {}", n);

    // The second call, nothing print
    let n = FOO.await;
    println!("The result of the second call: {}", n);
}

async_static


Ext Link: https://github.com/liangyongrui/async_static

评论区

写评论
作者 liangyongrui 2021-02-20 10:17

对对,我更新了一下,需要用到once_cell

例子中用到了 tokio 但是别的runtime也是可以的,使用的是调用时候的runtime

--
👇
c5soft: Cargo.toml

[dependencies]
async_static= { version="0.1.2" }
once_cell={version= "1.5.2"}
tokio = { version = "1.2.0", features = ["macros", "rt", "rt-multi-thread","time"]}
c5soft 2021-02-20 08:48

Cargo.toml

[dependencies]
async_static= { version="0.1.2" }
once_cell={version= "1.5.2"}
tokio = { version = "1.2.0", features = ["macros", "rt", "rt-multi-thread","time"]}
1 共 2 条评论, 1 页