相关疑难解决方法(0)

如何接受异步函数作为参数?

我想就像复制行为,并采取封闭/函数作为参数人体工程学map的作用:iterator.map(|x| ...)

我注意到一些库代码允许传入异步功能,但此方法不允许我传入参数:

pub fn spawn<F, T>(future: F) -> JoinHandle<T>
where
    F: Future<Output = T> + Send + 'static,
    T: Send + 'static,
Run Code Online (Sandbox Code Playgroud)
spawn(async { foo().await });
Run Code Online (Sandbox Code Playgroud)

我希望执行以下操作之一:

iterator.map(async |x| {...});
Run Code Online (Sandbox Code Playgroud)
async fn a(x: _) {}
iterator.map(a)
Run Code Online (Sandbox Code Playgroud)

closures asynchronous future rust async-await

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

如何在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
查看次数

如何将 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
查看次数

如何创建未来的 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
查看次数

FuturesUnordered 的生命周期问题

我试图将这些Readable实例存储在Coordinator结构上,并有一个schedule方法可以选择其中一个实例readables并将其推送到 FuturesUnordered 实例(也在 内部Coordinator)中以便稍后提取。问题是:由于生命周期错误,这无法编译

use bytes::Bytes;
use futures::prelude::stream::FuturesUnordered;
use std::future::Future;
use std::pin::Pin;

struct Readable {}

impl Readable {
    async fn read(&mut self) -> Result<Bytes, ()> {
        Err(())
    }
}

type Futures = FuturesUnordered<Pin<Box<dyn Future<Output = Result<Bytes, ()>> + Send>>>;

struct Coordinator {
    readers: Vec<Readable>,
    futures: Futures,
}

impl Coordinator {
    fn schedule(&mut self) {
        let reader = self.readers.get_mut(0).unwrap();
        let f = Box::pin(reader.read());
        self.futures.push(f);
    }
}
Run Code Online (Sandbox Code Playgroud)

错误

error[E0759]: `self` has an …
Run Code Online (Sandbox Code Playgroud)

lifetime self-reference rust

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

如何在异步函数中设置断点?

我有一个带有async我想要调试的方法的结构。我使用 gdb 通过调试构建设置断点。async以下是在该方法处停止时代码的样子Strct::async_method

0x5555557f4a6a <bin::Strct::async_method+26>            mov    QWORD PTR [rsp+0x10],rsi
0x5555557f4a6f <bin::Strct::async_method+31>            mov    QWORD PTR [rsp+0x18],rdx
0x5555557f4a74 <bin::Strct::async_method+36>            mov    BYTE PTR [rsp+0x112],0x0
0x5555557f4a7c <bin::Strct::async_method+44>            lea    rsi,[rsp+0x10]
0x5555557f4a81 <bin::Strct::async_method+49>            mov    QWORD PTR [rsp+0x8],rax
0x5555557f4a86 <bin::Strct::async_method+54>            call   0x5555557e6970 <core::future::from_generator>
Run Code Online (Sandbox Code Playgroud)

该代码调用的core::future::from_generator内容不是我想要调试的。暂停方法体执行的正确方法是什么async

gdb rust async-await

0
推荐指数
1
解决办法
1660
查看次数