gpt4 book ai didi

rust - FnOnce 的泛型,返回一个终生的 future

转载 作者:行者123 更新时间:2023-12-03 11:24:20 26 4
gpt4 key购买 nike

我有一个结构需要一个回调,该回调返回一个输出具有生命周期的 future :


struct Foo;
struct Bar;

struct Baz<F>
where F: for<'a> FnOnce(&'a Foo) -> impl std::future::Future<Output=&'a Bar> // ?
{
cb: F
}

这不能编译,自 impl 以来出现语法错误不能出现在特征边界中:
   Compiling playground v0.0.1 (/playground)
error[E0562]: `impl Trait` not allowed outside of function and inherent method return types
--> src/lib.rs:6:37
|
6 | where F: for<'a> FnOnce(&'a Foo) -> impl std::future::Future<Output=&'a Bar>,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

error: aborting due to previous error
这也不能编译:

struct Foo;
struct Bar;

struct Baz<O, F>
where
O: for<'a> std::future::Future<Output=&'a Bar>,
F: for<'b> FnOnce(&'b Foo) -> O,
{
cb: F
}
投诉 'a不被识别(生命周期 'a'b 将无关):
   Compiling playground v0.0.1 (/playground)
error[E0582]: binding for associated type `Output` references lifetime `'a`, which does not appear in the trait input types
--> src/lib.rs:7:36
|
7 | O: for<'a> std::future::Future<Output=&'a Bar>,
| ^^^^^^^^^^^^^^

error: aborting due to previous error
有没有办法指定这种关系?

最佳答案

这有点难看,但这是我能找到的最好方法(使用 struct Foo(Bar) 进行演示):
Playground

use std::future::Future;

struct Bar;
struct Foo(Bar);

trait FooClosure<'a> {
type Fut: Future<Output = &'a Bar>;

fn call(self, foo: &'a Foo) -> Self::Fut;
}

impl<'a, Fut: Future<Output = &'a Bar>, C: FnOnce(&'a Foo) -> Fut> FooClosure<'a> for C {
type Fut = Fut;

fn call(self, foo: &'a Foo) -> Fut {
self(foo)
}
}

struct Baz<F: for<'a> FooClosure<'a>>(F);

fn main() {
let closure: Box<dyn for<'a> FnOnce(&'a Foo) -> futures::future::Ready<&'a Bar>> =
Box::new(|foo| futures::future::ready(&foo.0));
let baz = Baz(closure);
}
我无法让编译器正确推断类型,所以我不得不将闭包包装为盒装 trait 对象。从理论上讲,这不应该是必要的,可能有办法避免这种情况,但我无法弄清楚。
注意:我认为有计划让您的原始代码工作而无需这种黑魔法。

关于rust - FnOnce 的泛型,返回一个终生的 future ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65316753/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com