为什么"the trait bound Future is not satisfied"在使用 .await 或在"join!



我正在开发一个异步Rust程序,但join!宏不起作用。.await也不起作用。我的问题在哪里?

我在官方文件中看到了一些例子。

这也不起作用:

#[async_std::main]
async fn main() {}

我没有使用Tokio或Hyper,因为它是一个简单的程序。

use async_std::task;
use futures::executor::block_on;
use futures::join;
use futures::stream::{FuturesUnordered, StreamExt};
use rand::distributions::{Distribution, Uniform};
use std::thread;
use std::time::{Duration, Instant};
fn main() {
let start = "bename Allah";
println!("{}", start);
fn fibonacci(n: u64) -> u64 {
if n <= 1 {
return 1;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
fn fib(n: u64) {
println!("Its : {}", fibonacci(n));
}
async fn calculate() {
let do1 = fib(45);
let do2 = fib(20);
join!(do1, do2);
}
calculate();
//i used block_on(calculate()) but got same error :(
}
[dependencies]
futures = "0.3.1"
rand = "0.7"
async-std = { version = "1.2", features = ["attributes"] }
surf = "1.0"

我得到这个错误:

error[E0277]: the trait bound `(): core::future::future::Future` is not satisfied
--> srcmain.rs:28:15
|
28 |         join!(do1,do2);
|               ^^^ the trait `core::future::future::Future` is not implemented for `()`
| 
::: C:UsersMahdi.cargoregistrysrcgithub.com-1ecc6299db9ec823futures-util-0.3.4srcfuturemaybe_done.rs:42:24
|
42 | pub fn maybe_done<Fut: Future>(future: Fut) -> MaybeDone<Fut> {
|                        ------ required by this bound in `futures_util::future::maybe_done::maybe_done`

您的问题可以简化为:

fn alpha() {}
async fn example() {
alpha().await;
}
error[E0277]: the trait bound `(): std::future::Future` is not satisfied
--> src/lib.rs:4:5
|
4  |     alpha().await;
|     ^^^^^^^^^^^^^ the trait `std::future::Future` is not implemented for `()`

您正试图等待某个未实现Future的东西。alpha的返回类型为()。您可能打算使您的函数async:

async fn alpha() {}
//^^^
async fn example() {
alpha().await;
}

另请参阅:

  • 使用TcpConnectionNew时,不满足trait绑定`((:futures::Future`
  • 没有为"std::result::result<"实现特征"std:;future::future";reqwest::响应,reqwest::错误>
  • 从"async fn"返回的future的具体类型是什么
  • Rust中async/await的目的是什么

值得指出的是,计算斐波那契数并不适合异步工作。另请参阅:

  • 在未来的rs中封装阻塞I/O的最佳方法是什么
shepmaster说得太对了!我找到了一个正确的新解决方案:
use std::thread;
fn main() {
let start = "bename Allah";
println!("{}", start);
fn fibonacci(n: u64) -> u64 {
if n <= 1 {
return 1;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
fn fib(n: u64) {
println!("Its : {}", fibonacci(n));
}
fn calculate() {
let do1 = thread::spawn (move || {
fib(45);
});
let do2 = thread::spawn (move || {
fib(20);
});
do1.join();
do2.join();
}
calculate();
}

相关内容

最新更新