如何为包含引用的结构实现 AsRef

How to implement AsRef for a struct containing references

如果我有一个包含如下引用的结构:

struct Struct<'a> {
    reference: &'a str
}

如何为 Struct 实现 AsRef?我试过这个:

impl<'a> AsRef<Struct<'a>> for Struct<'a> {
    fn as_ref(&self) -> &Struct {
        self
    }
}

但未能满足编译器要求:

cannot infer an appropriate lifetime for lifetime parameter in generic type due to conflicting requirements

使用 fn as_ref(&self) -> &Struct 时,编译器必须推断 return 类型中的(隐式)泛型生命周期,但未能这样做。编译器期望一个 Struct<'a> 但签名承诺一个自由参数。这就是为什么你得到

      expected fn(&Struct<'a>) -> &Struct<'a>
         found fn(&Struct<'a>) -> &Struct<'_>  // '_ is some anonymous lifetime,
                                               // which needs to come from somewhere

解决方法是将签名修改为returnStruct<'a>而不是Struct。更短更清晰:

impl<'a> AsRef<Struct<'a>> for Struct<'a> {
    fn as_ref(&self) -> &Self {  // Self is Struct<'a>, the type for which we impl AsRef
        self
    }
}