async fn Future是否為Send的取決于是否在.await點(diǎn)上保留非Send類型。編譯器盡其所能地估計(jì)值在.await點(diǎn)上的保存時(shí)間。
示例
- 源碼
use std::rc::Rc;
#[derive(Default)]
struct NotSend(Rc<()>);
async fn bar() {}
async fn foo() {
NotSend::default();
bar().await;
}
fn required_send(_: impl Send) {}
fn main() {
required_send(foo());
}
- 說明
上述代碼并不會(huì)報(bào)錯(cuò)。但是,如果我們將代碼foo函數(shù)修改為如下:
async fn foo() {
let x = NotSend::default();
bar().await;
}
- 原因分析
如果我們存儲(chǔ)了x變量,那么在await之前,x可能并不會(huì)drop,那么也就意味著可能會(huì)在線程之間傳遞。而Rc是不能在線程之間傳遞的。
- 解決方式
async fn foo() {
{
let x = NotSend::default();
}
bar().await;
}