Implement Borrow, Owned and Deref for custom types

Hello,

I have a set of structs that work in pair like this:

struct SomeStruct<'a> {
    param: Param,
    data: &'a [u8],
}

struct SomeStructBuf {
    param: Param,
    data: Vec<u8>,
}

Both structs have exactly the same semantics, and the borrowed version implement many accessors on the data field, sometimes using the param field. I'd like the owned version to coerce to the borrowed one, and things to work out nicely in the same spirit as String and &str.

If I hadn't the param field, I could have SomeStruct dynamically sized and do the same as the std library OsStr or Path. But given the param field, I can't construct such DST as the memory layout is not compatible (that's my understanding at least).
So in this case, the borrow method would not return a reference, but a struct holding a reference.

What are my options?
Please note that the borrowed version is not always built out of a owned version, but sometimes from a data stream received from a server.

You can't implement Borrow<SomeStruct> or Deref<Target=SomeStruct>, but you could create your own custom method that does something similar:

impl SomeStructBuf {
    fn borrow(&self) -> SomeStruct<'_> {
        SomeStruct { param: self.param, data: &self.data }
    }
}

If you need to implement Borrow in order to query a collection like HashMap or BTreeSet, you can use this trait object trick.

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.