泛型关联类型可能存在的时间不够长

编程入门 行业动态 更新时间:2024-10-27 10:27:08
本文介绍了泛型关联类型可能存在的时间不够长的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

以下面的例子(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 作为引用.但是,此代码无法编译.它给了我错误:

The GenericError has a lifetime to allow it to take Produce as a reference. However, this code doesn't compile. It gives me the error:

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.不过,我在弄清楚如何解决问题时遇到了麻烦.也许我的通用生命周期放错了地方?

This error makes sense to me because the GenericError doesn't have any restriction telling it that T must be 'a. I'm having trouble figuring out how to solve the problem though. Perhaps my generic lifetimes are misplaced?

我希望捕获的特征的特征是任何 Produce::CustomError 都应该能够在返回中捕获 self.也许我以错误的方式处理这个问题?

The feature of the trait I wish to capture is that any Produce::CustomError should be able to capture self in a return. Perhaps I am going about this in the wrong way?

推荐答案

没有 generic_related_types 的相同 trait 在 trait 本身中占用生命周期.

The same trait without generic_associated_types takes the lifetime in the trait itself.

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.

This tells the impl upfront that T that it must be 'a.

这篇关于泛型关联类型可能存在的时间不够长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 01:52:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1198672.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   时间

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!