Lifetimes implementing AsRef

Viewed 160

I need to create NewType wrappers for interfacing with FFI. I want to create an interface similar to Rust's String and str types, so I can have a wrapper for an owned type, and a wrapper for a reference. Because some times I'm dealing with references that came from raw pointers that the FFI library will free, and other times I need to take ownership so that rust will free the memory. I want to be able to easily use the methods on the reference type by implementing AsRef on the owned type, but I'm having an issue with lifetimes.

playground

pub struct MyInt(i64);

pub struct MyIntRef<'a>(&'a i64);

impl AsRef<MyIntRef<'_>> for MyInt {
    fn as_ref(&self) -> &MyIntRef<'_> {
        todo!()
    }
}

This code fails to compile with the following error:

= note: expected `fn(&MyInt) -> &MyIntRef<'_>`
           found `fn(&MyInt) -> &MyIntRef<'_>`

The error seems to indicate that I do have the correct signature. Why is this failing?

1 Answers

I think you've just got your trait parameter type mixed up.

pub struct MyInt(i64);

pub struct MyIntRef<'a>(&'a i64);

impl AsRef<i64> for MyInt {
    fn as_ref(&self) -> &i64 {
        &self.0
    }
}

impl<'a> AsRef<i64> for MyIntRef<'a> {
    fn as_ref(&self) -> &i64 {
        self.0
    }
}
Related