然而,在我的情况下,我会立即等待他们,所以我知道它不会超过当前的范围.
对于这一推理,有两种回应.
其一,您立即等待的事实与编译器执行的判断没有任何关系.tokio::spawn()
需要一个拥有其数据的future ,这只是一个事实--您如何使用它并不重要,或者换句话说,编译器甚至不会try 足够智能地覆盖这样的界限,即使在它看起来安全的地方也是如此.
另一种react 是,你所说的实际上并不是真的.是的,您立即等待结果,但这不能保证传递到spawn()
的future 不会超过当前作用域.等待future 只是意味着,如果等待的future Select 挂起,等待它的异步功能也会一起挂起.由Async函数创建的外部future 可能在等待完成之前被丢弃,在这种情况下,作用域在fut1
仍在运行时消失.例如:
// let's assume this function were allowed to compile
async fn foo() {
let mut i = 0;
tokio::spawn(async {
sleep(1).await;
i = 1;
}).await;
assert!(i == 1);
}
// this function is safe and compiles
async fn bar() {
{
// create the foo() future in an inner scope
let fut = foo();
// spin up the future created by `foo()` by polling it just once
Box::pin(fut)
.as_mut()
.poll(&mut Context::from_waker(&futures::task::noop_waker()));
// leave fut to go out of scope and get dropped
}
// what memory does `i = 1` modify after 1s?
}