特征中泛型引用的生命周期

Lifetime for ref to generic in trait

我正在尝试要求一个泛型类型可以通过 const ref 索引到另一个泛型:

struct A<T, I> where T: Index<&I> {
    t: T,
    some_more_uses_of_I...
}

它没有编译要求我为 &I 提供生命周期。当我将其更改为 &'_ I 时,编译器会抱怨“'_ 不能在此处使用”和“'_ 是保留的生命周期名称”。我怎样才能让它发挥作用?据我了解,生命周期没有真正的必要性,引用必须仅在 [] 执行期间存在,我相信我不应该将它绑定到任何其他对象。

这应该是编译

struct A<'a, T, I>
    where T: Index<&'a I> {
        t: T
    }

您可以在 https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#lifetime-annotations-in-struct-definitions

中查看更多信息

在不知道您如何使用这个结构的情况下,很难说。但听起来你可以使用 higher-ranked trait bound 这样约束在整个生命周期内都是通用的:

struct A<T, I> 
where 
    T: for<'a> Index<&'a I>
{
    t: T,
    some_more_uses_of_I...
}