我应该使用什么类型的向量来存储 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) 我想在一个中使用特征对象Vec.在C++中我可以使一个基类Thing从中导出Monster1和Monster2.然后我可以创建一个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()等,并实现它们的Monster1和Monster2.
我有一个程序,涉及检查复杂的数据结构,看它是否有任何缺陷.(这很复杂,所以我发布了示例代码.)所有检查都是彼此无关的,并且都将拥有自己的模块和测试.
更重要的是,每个检查都有自己的错误类型,其中包含有关每个数字检查失败方式的不同信息.我这样做而不是只返回一个错误字符串,所以我可以测试错误(这就是为什么Error依赖PartialEq).
我有特点Check和Error:
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) 我想要一个随机数发生器.既然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) 我想要生成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) 我有这个功能:
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 存储在向量中。
我试图将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) rust ×7
asynchronous ×2
types ×2
async-await ×1
collections ×1
future ×1
return-type ×1
traits ×1