#Help to fix some lifetime issues

4 messages · Page 1 of 1 (latest)

sharp hedge
#
pub trait Decode: Sized {
    fn decode(bytes: &[u8]) -> Result<Self>;
}

impl Decode for &str {
    fn decode(bytes: &[u8]) -> Result<&str> {
        str::from_utf8(bytes).map_err(Error::Utf8)
    }
}

Compiler errors:

error: `impl` item signature doesn't match `trait` item signature
error: found `fn(&'1 [u8]) -> std::result::Result<&'1 str, Error>`
note: expected signature `fn(&'1 [u8]) -> std::result::Result<&'2 str, Error>`
   found signature `fn(&'1 [u8]) -> std::result::Result<&'1 str, Error>`
error: expected `fn(&'1 [u8]) -> std::result::Result<&'2 str, Error>`
help: the lifetime requirements from the `impl` do not correspond to the requirements in the `trait`
help: consider borrowing this type parameter in the trait
lime rock
#

The issue here is that the Decode trait assumes that Self has nothing to do with bytes, i.e. that it doesn't borrow any data

#

To fix this, you'd need to update the trait and impl:

pub trait Decode<'a>: Sized {
    fn decode(bytes: &'a [u8]) -> Result<Self>;
}

impl<'a> Decode<'a> for &'a str {
    fn decode(bytes: &'a [u8]) -> Result<Self> {
        str::from_utf8(bytes).map_err(Error::Utf8)
    }
}

Now, Decode indicates that the value can be bounded by the lifetime of the bytes, which the &str is.

#

Note that it doesn't have to be bounded by the lifetime, so this is also valid:

impl<'a> Decode<'a> for Vec<u8> {
    fn decode(bytes: &'a [u8]) -> Result<Self> {
        Ok(Vec::from(bytes))
    }
}

The Vec has no lifetimes, but that's okay