相关疑难解决方法(0)

如何在Rust中将异步函数放入地图中?

为编写异步路由器时,我无法处理异步功能hyper

这段代码:

use std::collections::HashMap;
use std::future::Future;

type BoxedResult<T> = Result<T, Box<dyn std::error::Error + Send + Sync>>;
type CalcFn = Box<dyn Fn(i32, i32) -> dyn Future<Output = BoxedResult<i32>>>;

async fn add(a: i32, b: i32) -> BoxedResult<i32> {
    Ok(a + b)
}

async fn sub(a: i32, b: i32) -> BoxedResult<i32> {
    Ok(a - b)
}

fn main() {
    let mut map: HashMap<&str, CalcFn> = Default::default();
    map.insert("add", Box::new(add));
    map.insert("sub", Box::new(sub));

    println!("map size: {}", map.len());
}
Run Code Online (Sandbox Code Playgroud)

生成以下编译器错误:

use std::collections::HashMap;
use std::future::Future;

type …
Run Code Online (Sandbox Code Playgroud)

rust async-await

10
推荐指数
1
解决办法
176
查看次数

不能使用 `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
查看次数

标签 统计

rust ×2

async-await ×1

asynchronous ×1

types ×1