我有大致如下的tokio::main
#[tokio::main]
pub async fn my_tokio_main() {
let addr = "[::1]:9002";
let listener = TcpListener::bind(&addr).await.expect("Can't listen");
while let Ok((stream, _)) = listener.accept().await {
// Handle the connection
}
}使用大致如下的测试:
#[tokio::test]
async fn test_hello() {
task::spawn(my_tokio_main());
// ^^^^^^^^^^^^^^^ `()` is not a future
}但是,在构建测试时,编译器会抱怨()不是未来。
我的理解是,因为my_tokio_main()是async,所以它确实返回了未来。为什么编译器在这里抱怨呢?
发布于 2021-04-10 23:19:48
在#[tokio::main]函数上有main属性。该属性将将函数转换为同步函数,该函数创建tokio运行时,并将调用runtime.block_on(future),其中future是定义的异步函数的结果。
因此,实际生成的my_tokio_main是同步的。您可以分离tokio::main包装器和async函数定义,以便从另一个异步函数调用异步函数。
https://stackoverflow.com/questions/67040116
复制相似问题