【问题标题】:What's the meaning of bounding a trait by its own generic lifetime (trait Bar<'a>: 'a)?用它自己的通用生命周期来限制一个特征是什么意思(trait Bar<'a>: 'a)?
【发布时间】:2021-01-06 14:51:12
【问题描述】:

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

trait Bar<'a>: 'a { }

我还没有想到这种情况。

我直观地解释一个类型的“生命周期”如下:

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

trait Bar&lt;'a&gt;: 'a { } 是什么意思——有一个方法使用借用类型的参数?

和这个一样吗?

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

我想不出上述含义的用法,这种情况的示例用法是什么?我很难理解“特征的终身参数”的含义。

【问题讨论】:

    标签: generics rust traits lifetime


    【解决方案1】:

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

    例如,绑定在 trait 上的 'static 生命周期意味着它不能由包含不超过 'static 的引用的任何结构体实现。

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

    trait Bar<'a> { }
    

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

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

    这表示 any HasRef 结构——即使是生命周期很短的结构——也实现了 Bar&lt;'static&gt; 特征。

    改写

    trait Bar<'a>: 'a { }
    

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

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

    【讨论】:

    • 啊哈。我可以通过直接在Trait 中实现lifetimebound 来省略dyn Trait 的生命周期绑定!谢谢。
    • 然而,这对我来说很模糊。 (一大堆一辈子的东西......)
    猜你喜欢
    • 2021-09-18
    • 2021-04-08
    • 1970-01-01
    • 2015-08-26
    • 2020-02-15
    • 2016-12-14
    • 1970-01-01
    • 2021-03-31
    相关资源
    最近更新 更多