fabiim
fabiim

Reputation: 943

How to implement AsRef for a struct containing references

If I have a struct containing a reference like so:

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

How can I implement AsRef for the Struct? I tried this:

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

but it fails to satisfy the compiler requirements:

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

Upvotes: 3

Views: 2333

Answers (1)

user2722968
user2722968

Reputation: 16515

With fn as_ref(&self) -> &Struct the compiler has to infer the (implicit) generic lifetime in the return type and fails to do so. The compiler is expecting a Struct<'a> but the signature promises a free parameter. That's why you get

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

The solution is to modify the signature to return Struct<'a> instead of Struct. Even shorter and more clear:

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
    }
}

Upvotes: 4

Related Questions