Impl trait for struct with lifetime parameter

pub trait Key {
    fn from_u8(key: &[u8]) -> Self;
    fn as_slice<T, F: Fn(&[u8]) -> T>(&self, f: F) -> T;
}

pub fn from_u8<K: Key>(key: &[u8]) -> K {
    Key::from_u8(key)
}

struct MyKey<'a>(&'a [u8]);

impl Key for MyKey<'_> {
    fn from_u8(key: &[u8]) -> Self {
        MyKey(key)
    }

    fn as_slice<T, F: Fn(&[u8]) -> T>(&self, f: F) -> T {
        f(&self.0)
    }
}

How can I impl from_u8 for MyStruct, the compiler tells that "cannot infer an appropriate lifetime for lifetime parameter 'a due to conflicting requirements".

You can make the trait generic on the lifetime.

1 Like

If the trait is from outter crate, it can't be changed, is there any way to pass the compiling?

Only if you do something like owning the data instead. The trait function signature as-is says "I can make Self out of a slice with an arbitrary lifetime".

1 Like

If the trait declares that from_u8()'s key parameter has a lifetime shorter than your Key type it means you'll need to make your own copy of the key.

Get it, thanks very much.

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.