【问题标题】:How do I indicate a lifetime bound on a type parameter when using generic associated types?使用泛型关联类型时,如何指示类型参数的生命周期?
【发布时间】:2020-07-22 12:29:30
【问题描述】:

我正在尝试为具有泛型类型的结构实现具有泛型关联类型的特征。我正在使用夜间版本1.47.0-nightly (2020-07-20 f9a3086363f214f2b56b)

我有结构 S1S2,一个带有 GAT 的 trait 和一个实现:

#![allow(incomplete_features)]
#![feature(generic_associated_types)]

use core::marker::PhantomData;

struct S1<T>(PhantomData<T>);
struct S2<'a, T: 'a>(PhantomData<(T, &'a ())>);

trait MyTrait {
    type A<'a>;
}

impl MyTrait for S1<f64> {
    type A<'a> = S2<'a, f64>;
}

这可行,但我想为通用 T 实现特征:

impl<T> MyTrait for S1<T> {
    type A<'a> = S2<'a, T>;
}

Playground

我现在需要指出T 的寿命与'a 一样长,这是S2 的定义所要求的:

error[E0309]: the parameter type `T` may not live long enough
  --> src/lib.rs:14:5
   |
13 | impl<T> MyTrait for S1<T> {
   |      - help: consider adding an explicit lifetime bound...: `T: 'a`
14 |     type A<'a> = S2<'a, T>;
   |     ^^^^^^^^^^^^^^^^^^^^^^^ ...so that the type `T` will meet its required lifetime bounds

如何做到这一点?

我找到了Generic associated type may not live long enough,但它可能已经过时,因为它声称代码尚未实现。但是,为什么像this 这样的复杂代码会编译(并按预期工作)?

【问题讨论】:

  • 添加T: 'static 绑定的潜在缺点是什么?
  • 如果T 的寿命与'a 一样长,尽可能 'a,然后T: 'static

标签: generics rust traits lifetime generic-associated-types


【解决方案1】:
impl<T> MyTrait for S1<T> {
    type A<'a> = S2<'a, T>;
}

T 在整个实现中是固定的,包括它的生命周期。但是,'a 的生命周期在使用时会有所不同。如果您需要T 的生命周期比'a 长,那么对于所有可能的生命周期都必须如此。因此,在不更改该实现中的其他内容的情况下,T 可以拥有的唯一生命周期是 'static

impl<T: 'static> MyTrait for S1<T> {
    type A<'a> = S2<'a, T>;
}

也就是说,T 不能包含除了对静态变量的引用之外的任何引用。

还请注意,GAT 尚未稳定,该功能可能仍不完整。它处于您可以玩弄它以了解它可以做什么的阶段,但还没有为现实世界做好准备。

【讨论】:

    猜你喜欢
    • 2016-02-17
    • 1970-01-01
    • 2021-05-24
    • 2018-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-13
    相关资源
    最近更新 更多