用它自己的通用生命周期(trait Bar<'a>: 'a)来限制一个 trait 是什么意思?

What's the meaning of bounding a trait by its own generic lifetime (trait Bar<'a>: 'a)?

我在the official reference看到过这种代码:

trait Bar<'a>: 'a { }

没想过这种情况

我对一个类型的“lifetime bound”的直觉解释如下:

some_reference: &'a Some_Type = &instance_of_Some_Type;
T: 'a // T is borrowed by "instance_of_Some_Type"

trait Bar<'a>: 'a { } 是什么意思 — 有一个方法使用参数借用类型?

和这个一样吗?

impl Bar<'a> for Another_Type
where
    Another_Type: 'a
{
}

我想不出上面蕴涵的用法,请问这个case的用法是什么?我很难理解“特征的生命周期参数”的含义。

特征的生命周期绑定是关于实现该特征的某种类型内部的引用。

例如,特征上的 'static 生命周期绑定意味着它不能由任何包含不超过 'static.

的引用的结构实现。

让我们以没有生命周期限制的例子为例:

trait Bar<'a> { }

这是一个基于生命周期 'a 的参数化特征,但不要求它的实现实际超过 'a,所以我们可以这样做:

struct HasRef<'b>(&'b i32);
impl Bar<'static> for HasRef<'_> { }

表示 any HasRef 结构——即使是生命周期很短的结构——实现了 Bar<'static> 特征。

改写

trait Bar<'a>: 'a { }

表示任何实现 Bar<'a> 的类型必须至少与 'a 一样长,这可能更有意义。

(这些边界对于 trait 对象(类型如 dyn Trait)尤其重要,因为只有 trait 本身才能让编译器了解此 trait 对象内引用的生命周期。)