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.
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?
'_
means two different lifetimes in the two places you have it, but beyond that, how exactly do you intend to fill in thattodo!()
? You can't create aMyIntRef
inside the function and return a reference to it. Take another look at the relationship betweenstr
andString
-- note that neither of them has a lifetime parameter. – trentclCString
andCStr
, (str
is a primitive type, butCStr
is pure Rust). – rodrigoi64
in your snippets is a placeholder. – rodrigo