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);
}
Ext Link: https://github.com/liangyongrui/async_static
1
共 2 条评论, 1 页
评论区
写评论对对,我更新了一下,需要用到once_cell
例子中用到了 tokio 但是别的runtime也是可以的,使用的是调用时候的runtime
--
👇
c5soft: Cargo.toml
Cargo.toml