Rust.Struct的通用类型参数,用于Fn成员签名,需要命名的寿命。在Fn成员签名中使用的Struct通用类型参数需要命名的寿命

问题描述 投票:0回答:1

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

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 lifetime
1个回答
0
投票

不幸的是,你想做的事情目前在Rust中是行不通的。当一个结构在一个引用上通用时,该引用至少要在结构的生命周期内生存。所以,如果你听编译器的,它不会做你想要的事情。游戏场链接

正因为如此,你要么必须使 funBox<dyn Fn(&mut T)> 或将你的结构改为通用于任何东西。

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

type FooI = Foo<i32>;

游戏场链接

我还没有看到上下文中的代码,但这可能是一个很好的机会来使用 特质.

© www.soinside.com 2019 - 2024. All rights reserved.