Rust:用于 Fn 成员签名的结构泛型类型参数需要命名生命周期

Rust: Struct generic type parameter for use in Fn member signature requires named lifetime

我有一个带有函数成员的结构:

struct Foo<T> {
    fun: Box<dyn Fn(T)>,
}

type FooI = Foo<&mut i32>;

这行不通:

error[E0106]: missing lifetime specifier
 --> src/main.rs:5:17
  |
5 | type FooI = Foo<&mut i32>;
  |                 ^ expected named lifetime parameter
  |
help: consider introducing a named lifetime parameter
  |
5 | type FooI<'a> = Foo<&'a mut i32>;

但我不希望 FooI 在 T 的生命周期内被参数化,我只希望 T 的实例比对 Foo.fun 的调用更有效。我将如何对其进行编码?

很遗憾,您正在尝试做的事情目前不适用于 Rust。当一个结构对一个引用具有通用性时,该引用必须至少在该结构的生命周期内存在。所以,如果你听了编译器,它不会做你想做的事: playground link

因此,您要么必须将 fun 设为 Box<dyn Fn(&mut T)>,要么将您的结构更改为通用的。

struct Foo<T> {
    fun: Box<dyn Fn(&mut T)>
}

type FooI = Foo<i32>;

Playground Link

我没有在上下文中看到代码,但这可能是使用 traits 的好机会。