通用关联类型可能不够长寿

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

以下面的例子为例(游乐场):

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

trait Produce {
    type CustomError<'a>;

    fn produce<'a>(&'a self) -> Result<(), Self::CustomError<'a>>;
}

struct GenericProduce<T> {
    val: T,
}

struct GenericError<'a, T> {
    producer: &'a T,
}

impl<T> Produce for GenericProduce<T> {
    type CustomError<'a> = GenericError<'a, T>;

    fn produce<'a>(&'a self) -> Result<(), Self::CustomError<'a>> {
        Err(GenericError{producer: &self.val})
    }
}

GenericError 有生之年,让它拿 Produce 作为参考。然而,这段代码无法编译。它给了我错误。

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

这个错误对我来说是有意义的,因为 GenericError 没有任何限制,告诉它说 T 必须 'a. 不过我很难想出如何解决这个问题。也许是我的通用寿命放错了位置?

我想抓住的特征是,任何的 Produce::CustomError 应能捕捉到 self 以示回报。也许我的方法不对?

rust traits generic-associated-types
1个回答
0
投票

同样的特质,没有 generic_associated_types 以特质本身的一生。

trait Produce<'a> {
    type CustomError;

    fn produce(&'a self) -> Result<(), Self::CustomError>;
}

struct GenericProduce<T> {
    val: T,
}

struct GenericError<'a, T> {
    producer: &'a T,
}

impl<'a, T: 'a> Produce<'a> for GenericProduce<T> {
    type CustomError = GenericError<'a, T>;

    fn produce(&'a self) -> Result<(), Self::CustomError> {
        Err(GenericError{producer: &self.val})
    }
}

这在前期就告诉了内涵 T 必须 'a.

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