相关疑难解决方法(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
查看次数

为什么impl trait不能用于返回多个/条件类型?

我想要一个随机数发生器.既然OsRng::new()可能会失败,我想回到以下情况,thread_rng()如果我必须:

extern crate rand; // 0.6.5

use rand::{rngs::OsRng, thread_rng, RngCore};

fn rng() -> impl RngCore {
    match OsRng::new() {
        Ok(rng) => rng,
        Err(e) => thread_rng(),
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我收到此错误消息,我无法理解:

error[E0308]: match arms have incompatible types
 --> src/lib.rs:6:5
  |
6 | /     match OsRng::new() {
7 | |         Ok(rng) => rng,
8 | |         Err(e) => thread_rng(),
  | |                   ------------ match arm with an incompatible type
9 | |     }
  | |_____^ expected struct `rand::rngs::OsRng`, found struct `rand::prelude::ThreadRng` …
Run Code Online (Sandbox Code Playgroud)

return-type traits rust

8
推荐指数
2
解决办法
1208
查看次数

标签 统计

rust ×2

asynchronous ×1

control-flow ×1

future ×1

return-type ×1

traits ×1