我有一个返回标准 Future 的异步特征方法:
Pin<Box<dyn Future<Output = Result<Vec<ResultType>, Box<(dyn Error + 'static)>>> + Send>>
ResultType
是 Sync + Send
特征的关联类型。
请注意,此类型不是取消固定。
我想从 actix 处理程序调用它,然后对结果做一些事情。
例如:
impl StreamHandler<ws::Message, ws::ProtocolError> for MyActor {
fn handle(&mut self, msg: ws::Message) {
let fut = get_future();
let actor_fut = fut
.into_actor(&self)
.map(|r, _actor, ctx| {
ctx.text(r.map(|| ...))
});
ctx.spawn(actor_fut);
}
}
这失败了,因为 into_actor
取得了 future 的所有权,这是 Pin
不允许的。清理后的错误消息如下所示:
error[E0599]: no method named `into_actor` found for type `Pin<Box<dyn Future<Output = Result<Vec<ResultType>, Box<dyn Error>>> + Send>>` in the current scope
--> src/app_socket.rs:194:26
|
194 | .into_actor(&self)
| ^^^^^^^^^^ method not found in `Pin<Box<dyn Future<Output = Result<Vec<ResultType>, Box<dyn Error>>> + Send>>`
|
= note: the method `into_actor` exists but the following trait bounds were not satisfied:
`&dyn Future<Output = Result<std::vec::Vec<ResultType>, std::boxed::Box<dyn std::error::Error>>> + Send : WrapFuture<_>`
`&dyn Future<Output = Result<std::vec::Vec<ResultType>, std::boxed::Box<dyn std::error::Error>>> + Send : WrapStream<_>`
`&mut dyn Future<Output = Result<std::vec::Vec<ResultType>, std::boxed::Box<dyn std::error::Error>>> + Send : WrapFuture<_>`
`&mut dyn Future<Output = Result<std::vec::Vec<ResultType>, std::boxed::Box<dyn std::error::Error>>> + Send : WrapStream<_>`
`&mut Pin<std::boxed::Box<dyn Future<Output = Result<std::vec::Vec<ResultType>, std::boxed::Box<dyn std::error::Error>>> + Send>> : WrapFuture<_>`
`&mut Pin<std::boxed::Box<dyn Future<Output = Result<std::vec::Vec<ResultType>, std::boxed::Box<dyn std::error::Error>>> + Send>> : WrapStream<_>`
`&Pin<std::boxed::Box<dyn Future<Output = Result<std::vec::Vec<ResultType>, std::boxed::Box<dyn std::error::Error>>> + Send>> : WrapFuture<_>`
`&Pin<std::boxed::Box<dyn Future<Output = Result<std::vec::Vec<ResultType>, std::boxed::Box<dyn std::error::Error>>> + Send>> : WrapStream<_>`
`dyn Future<Output = Result<std::vec::Vec<ResultType>, std::boxed::Box<dyn std::error::Error>>> + Send : WrapFuture<_>`
`dyn Future<Output = Result<std::vec::Vec<ResultType>, std::boxed::Box<dyn std::error::Error>>> + Send : WrapStream<_>`
`Pin<std::boxed::Box<dyn Future<Output = Result<std::vec::Vec<ResultType>, std::boxed::Box<dyn std::error::Error>>> + Send>> : WrapFuture<_>`
`Pin<std::boxed::Box<dyn Future<Output = Result<std::vec::Vec<ResultType>, std::boxed::Box<dyn std::error::Error>>> + Send>> : WrapStream<_>`
我该怎么做?
最佳答案
实际的问题不是 future 被固定了,而是它实现了错误的 future trait。
This section on Pinning解释说 poll
为 Pin<ref T: Future>
实现.
因此,into_actor
签名self: impl Future -> WrapFuture<_>
很好。问题是 async
方法返回一个 future 的实现 std::future::Future
同时 into_actor
预计 futures01::future::Future
.
调用 .compat()
打电话前关于 future .into_actor
解决问题。
参见 this post有关转换 future 的更多详细信息。
关于rust - 我如何从 actix 处理程序中调用固定的 future ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58332707/