相关疑难解决方法(0)

我如何有条件地退回不同类型的期货?

我有一个方法,根据谓词,将返回一个未来或另一个.换句话说,返回未来的if-else表达式:

extern crate futures; // 0.1.23

use futures::{future, Future};

fn f() -> impl Future<Item = usize, Error = ()> {
    if 1 > 0 {
        future::ok(2).map(|x| x)
    } else {
        future::ok(10).and_then(|x| future::ok(x + 2))
    }
}
Run Code Online (Sandbox Code Playgroud)

这不编译:

error[E0308]: if and else have incompatible types
  --> src/lib.rs:6:5
   |
6  | /     if 1 > 0 {
7  | |         future::ok(2).map(|x| x)
8  | |     } else {
9  | |         future::ok(10).and_then(|x| future::ok(x + 2))
10 | |     }
   | |_____^ expected …
Run Code Online (Sandbox Code Playgroud)

asynchronous future control-flow rust

13
推荐指数
1
解决办法
1463
查看次数

如何等待一个盒装未来的结果?

use futures::{future, Future};

fn test() -> Box<dyn Future<Output = bool>> {
    Box::new(future::ok::<bool>(true))
}

async fn async_fn() -> bool {
    let result: bool = test().await;
    return result;
}

fn main(){
    async_fn();
    println!("Hello!");
}
Run Code Online (Sandbox Code Playgroud)

操场

错误:

use futures::{future, Future};

fn test() -> Box<dyn Future<Output = bool>> {
    Box::new(future::ok::<bool>(true))
}

async fn async_fn() -> bool {
    let result: bool = test().await;
    return result;
}

fn main(){
    async_fn();
    println!("Hello!");
}
Run Code Online (Sandbox Code Playgroud)

future rust async-await

12
推荐指数
2
解决办法
3781
查看次数

如何将 Future 作为函数参数传递?

我习惯了 Scala 的类型,在这种类型Future中,您可以包装要返回的任何对象来指定它。Future[..]

我的 Rust 函数hello返回Query,但我似乎无法将该结果作为 type 的参数传递Future<Output = Query>。为什么不呢?我应该如何更好地输入它?

当我尝试将未来作为参数传递时,就会发生失败:

use std::future::Future;

struct Person;
struct DatabaseError;

type Query = Result<Vec<Person>, DatabaseError>;

async fn hello_future(future: &dyn Future<Output = Query>) -> bool {
    future.await.is_ok()
}

async fn hello() -> Query {
    unimplemented!()
}

async fn example() {
    let f = hello();
    hello_future(&f);
}

fn main() {}
Run Code Online (Sandbox Code Playgroud)

编译失败并出现以下错误:

error[E0277]: `&dyn Future<Output = Result<Vec<Person>, DatabaseError>>` is not a future
 --> src/main.rs:9:5
  |
9 | …
Run Code Online (Sandbox Code Playgroud)

future rust rust-tokio tokio-postgres

6
推荐指数
1
解决办法
3202
查看次数