gpt4 book ai didi

rust - 通用关联类型的生命周期可能不够长

转载 作者:行者123 更新时间:2023-12-03 11:39:30 26 4
gpt4 key购买 nike

请看以下示例(Playground):

#![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。也许我会以错误的方式处理此问题?

最佳答案

没有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

关于rust - 通用关联类型的生命周期可能不够长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62316153/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com