相关疑难解决方法(0)

从 `async fn` 返回的 future 的具体类型是什么?

我应该使用什么类型的向量来存储 future?

我尝试在同一个 URL 上发出多个并发请求,并将所有 future 保存到向量中以与join_all.

如果我没有明确设置向量的类型,则一切正常。我知道 Rust 可以找到变量的正确类型。CLion 确定向量类型为Vec<dyn Future<Output = ()>>,但是当我尝试自己设置类型时,它给了我一个错误:

error[E0277]: the size for values of type `dyn core::future::future::Future<Output = ()>` cannot be known at compilation time
  --> src/lib.rs:15:23
   |
15 |     let mut requests: Vec<dyn Future<Output = ()>> = Vec::new();
   |                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
   |
   = help: the trait `std::marker::Sized` is not implemented for `dyn core::future::future::Future<Output = ()>`
   = note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
   = …
Run Code Online (Sandbox Code Playgroud)

asynchronous future rust

12
推荐指数
1
解决办法
1万
查看次数

如何创建异构的对象集合?

我想在一个中使用特征对象Vec.在C++中我可以使一个基类Thing从中导出Monster1Monster2.然后我可以创建一个std::vector<Thing*>.Thing对象必须存储一些数据,例如x : int, y : int,派生类需要添加更多数据.

目前我有类似的东西

struct Level {
    // some stuff here
    pub things: Vec<Box<ThingTrait + 'static>>,
}

struct ThingRecord {
    x: i32,
    y: i32,
}

struct Monster1 {
    thing_record: ThingRecord,
    num_arrows: i32,
}

struct Monster2 {
    thing_record: ThingRecord,
    num_fireballs: i32,
}
Run Code Online (Sandbox Code Playgroud)

我定义了一个ThingTrait与方法get_thing_record(),attack(),make_noise()等,并实现它们的Monster1Monster2.

rust

11
推荐指数
1
解决办法
2501
查看次数

如何使用相关类型的对象向量?

我有一个程序,涉及检查复杂的数据结构,看它是否有任何缺陷.(这很复杂,所以我发布了示例代码.)所有检查都是彼此无关的,并且都将拥有自己的模块和测试.

更重要的是,每个检查都有自己的错误类型,其中包含有关每个数字检查失败方式的不同信息.我这样做而不是只返回一个错误字符串,所以我可以测试错误(这就是为什么Error依赖PartialEq).

我的代码到目前为止

我有特点CheckError:

trait Check {
    type Error;
    fn check_number(&self, number: i32) -> Option<Self::Error>;
}

trait Error: std::fmt::Debug + PartialEq {
    fn description(&self) -> String;
}
Run Code Online (Sandbox Code Playgroud)

两个示例检查,带有错误结构.在此示例中,如果数字为负数或偶数,我想显示错误:


#[derive(PartialEq, Debug)]
struct EvenError {
    number: i32,
}
struct EvenCheck;

impl Check for EvenCheck {
    type Error = EvenError;

    fn check_number(&self, number: i32) -> Option<EvenError> {
        if number < 0 {
            Some(EvenError { number: number })
        } else {
            None
        }
    }
}

impl …
Run Code Online (Sandbox Code Playgroud)

collections types rust

11
推荐指数
2
解决办法
2640
查看次数

为什么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
查看次数

如何从返回异步的闭包 Vec 中加入_all?

我想要生成Vec.awaitS和与执行它们join_all

use futures::future::join_all; // 0.3.5
use std::future::Future;

async fn hello(name: &str) -> String {
    format!("Hello {}!", name)
}

async fn main() {
    let urls = vec!["Peter", "Hans", "Jake"];
    let mut requests: Vec<Box<dyn Fn() -> Box<dyn Future<Output = String>>>> = vec![];
    for url in urls {
        requests.push(Box::new(|| Box::new(hello(&url))));
    }
    let responses: Vec<String> = join_all(requests).await;

    println!("Response: {:?}", responses);
}
Run Code Online (Sandbox Code Playgroud)

我收到错误消息:

error[E0277]: `dyn std::ops::Fn() -> std::boxed::Box<dyn futures::Future<Output = std::string::String>>` cannot be unpinned
  --> src/main.rs:15:45
   |
15 | …
Run Code Online (Sandbox Code Playgroud)

rust async-await

5
推荐指数
1
解决办法
939
查看次数

如何创建未来的 Vec

我有这个功能:

async fn get_events(r: RequestBuilder) -> Result<Vec<RepoEvent>, reqwest::Error> {
    Ok(r.send().await?.json::<Vec<RepoEvent>>().await?)
}
Run Code Online (Sandbox Code Playgroud)

我想存储一个Vecfuture 并等待它们全部:

let mut events = vec![];
for i in 1..=x {
    let req: RequestBuilder = client.get(&format!("https://example.com/api?page={}", i));

    events.append(get_events(req));
}
try_join_all(events).await.unwrap();
Run Code Online (Sandbox Code Playgroud)

我得到一个E0308: expected mutable reference, found opaque type.

应该是什么类型events

我可以通过推断类型来解决问题:

let events = (1..=x).map(|i| {
    let req: RequestBuilder = client.get(&format!("https://example.com/api?page={}", i));

    get_events(req);
});
Run Code Online (Sandbox Code Playgroud)

但我真的很想知道如何将 future 存储在向量中。

rust rust-async-std

5
推荐指数
0
解决办法
1638
查看次数

不能使用 `impl Future` 在向量中存储异步函数

我试图将async函数存储在向量中,但似乎impl不能在向量类型定义中使用:

use std::future::Future;

fn main() {
    let mut v: Vec<fn() -> impl Future<Output = ()>> = vec![];

    v.push(haha);
}

async fn haha() {
    println!("haha");
}
Run Code Online (Sandbox Code Playgroud)
error[E0562]: `impl Trait` not allowed outside of function and inherent method return types
 --> src/main.rs:4:28
  |
4 |     let mut v: Vec<fn() -> impl Future<Output = ()>> = vec![];
  |                            ^^^^^^^^^^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

如何在向量中写入类型?

我发现使用类型别名可能有一个解决方法,所以我更改了代码:

use std::future::Future;

type Haha = impl Future<Output = ()>;

fn main() {
    let mut v: Vec<fn() -> Haha> …
Run Code Online (Sandbox Code Playgroud)

types asynchronous rust

4
推荐指数
2
解决办法
3122
查看次数