Problem with convert String to bytes

I tried with this:

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

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

2 Likes

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 https://github.com/marti1125/cli-guide_server/blob/master/src/main.rs#L15
let f: &'static [u8] to let f: &[u8]