feat: add async fn

This commit is contained in:
2024-03-09 13:14:31 +08:00
parent 0d1e08fcd1
commit bb36536347
3 changed files with 478 additions and 0 deletions

View File

@@ -0,0 +1,48 @@
async fn action(input: Option<i32>) -> Option<String> {
// 若 input输入是None则返回 None
// 事实上也可以这么写: `let i = input?;`
let _i = match input {
Some(input) => input,
None => return None,
};
// 这里定义一些逻辑
Some("test".into())
}
#[tokio::main]
async fn main() {
let (tx, mut rx) = tokio::sync::mpsc::channel(128);
let mut done = false;
let operation = action(None);
tokio::pin!(operation);
tokio::spawn(async move {
let _ = tx.send(1).await;
let _ = tx.send(3).await;
let _ = tx.send(2).await;
});
loop {
tokio::select! {
res = &mut operation, if !done => {
println!("res = &mut operation, done={}", done);
done = true;
if let Some(v) = res {
println!("GOT = {}", v);
return;
}
}
Some(v) = rx.recv() => {
println!("Some(v={}) = rx.recv()", v);
if v % 2 == 0 {
// `.set` 是 `Pin` 上定义的方法
operation.set(action(Some(v)));
done = false;
}
}
}
}
}