ToOwned and AsRef implementation

PressRex profile image
by PressRex
ToOwned and AsRef implementation

Hi everybody,

I tried to implement AsRef and ToOwned traits for two structs that hold OsStr/OsString but I can't figure out how to configure lifetimes for it. Could you please tell me is it possible to impl these traits?

Thank you.

pub struct MyStringBuf {
    data: OsString,
    // ... other fields
}
pub struct MyString<'a> {
    data: &'a OsStr,
    // ... other fields
}
impl<'a> AsRef<MyString<'a>> for OsStr {
    fn as_ref(&self) -> &MyString<'a> {
        &MyString { data: self } // lifetime error
    }
}
impl<'a> Borrow<MyString<'a>> for MyStringBuf {
    fn borrow(&self) -> &MyString<'a> {
        &MyString { data: self.data.as_os_str() } // lifetime error
    }
}
impl<'a> ToOwned for MyString<'a> {
    type Owned = MyStringBuf;

    fn to_owned(&self) -> Self::Owned {
        MyStringBuf { data: self.data.to_owned() }
    }
}

Source: View source

PressRex profile image
by PressRex

Subscribe to New Posts

Lorem ultrices malesuada sapien amet pulvinar quis. Feugiat etiam ullamcorper pharetra vitae nibh enim vel.

Success! Now Check Your Email

To complete Subscribe, click the confirmation link in your inbox. If it doesn’t arrive within 3 minutes, check your spam folder.

Ok, Thanks

Read More