Lifetime error and understanding (E0495)

I am trying to understand why this doesn't work but can't for the life of my figure it out. I suspect it has something to do with how the Bytes::from is instantiated in from_str and that its meant to live past the lifetime of that function but I am not sure how to resolve that.

use bytes::{Bytes};
use std::str::FromStr;
use std::convert::TryFrom;

struct Address(Bytes);

impl FromStr for Address {
    type Err = &'static str;

    fn from_str(src: &str) -> Result<Self, Self::Err> {
        Address::try_from(Bytes::from(src))
    }
}

impl TryFrom<Bytes> for Address {
    type Error = &'static str;

    fn try_from(bytes: Bytes) -> Result<Self, Self::Error> {
        Ok(Address(bytes))
    }
}

fn main() {
    let address = Address::from_str("test");
}

Thanks
Matt

Ok I appear to have got it working by making the str to_owned()

But I am not sure exactly why that works

This is because the Bytes::from method requires a 'static string.

1 Like

Thanks. Is to_owned the most correct way to handle this?

I prefer to to_string and to_vec over to_owned due to being more explicit, but yes.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.