我在学习 Rust ,我原来是学习Go的。
使用 Go 很容易在 goroutine 中启动一个函数,即使我返回父函数,例如:
func doSomething() {
// do something
go func() {
// do something longer
// this doesn't block doSomething and also handles optional errors
}()
return // something
}
我怎样才能在 Rust 中做到这一点?
假设我有这个代码:
#[tokio::main]
async fn main() {
doSomething().await;
}
async fn doSomething() {
// do something
// How to start something longer here?
// I don't want to block doSomething function here, this is only a background task I need to start.
return // something
}
首先。您必须使用await语法。所以你的主要功能应该是这样的 Futurefuture.await
#[tokio::main]
async fn main() {
doSomething().await;
}
```rust
至于您的主要问题async是生锈设计中的非阻塞。如果一个未来还没有准备好取得进展,它会返回给调度程序,同时另一个未来可能会运行。我猜你想生成另一个将同时运行到未来的任务。要做到这一点(因为您使用的是 tokio,所以其他执行器有自己的功能)。所以你的例子可以这样重写:
```rust
async fn foo() {
// does some work
}
async fn doSomething() {
// do something
tokio::spawn(async {
foo().await;
});
return // something
}
```rust
如果您刚开始学习异步 rust,那么我建议您阅读 Tokio 的异步教程