Problem with convert String to bytes

I tried with this:

let mut l = String::from("hello");
let f: &'static [u8] = l.as_bytes();

src/ 41:33 error: `l` does not live long enough
src/     let mut f: &'static [u8] = l.as_bytes();
note: reference must be valid for the static lifetime...
src/ 58:2 note: ...but borrowed value is only valid for the block suffix following statement 3 at 40:38
src/     let mut l = String::from("hello");
src/     let mut f: &'static [u8] = l.as_bytes();

Your l is an owned String. It lives as long as the scope it's created in. However, you want your f to have 'static lifetime, which means it needs to live as long as your program. These are conflicting requirements, which is what the compiler tells you.

Either remove the String and just use a let f : &'static str = "hello" (which already has static lifetime, note that you can remove the type here, it's just for the sake of this explanation), or reduce the lifetime of f. Note that in the former case, you cannot mutate your string, and in the latter case, you cannot do anything with f after it goes out of scope.


In this case, if you'd like a &'static [u8], you can also do this:

static f: &'static [u8] = b"hello";

I removed static from
let f: &'static [u8] to let f: &[u8]