Search code examples
rust

Make a String "permanent" in Rust


In my example, I'm grabbing an environment variable and passing that into a Reqwest header:

let token: String = String::from(
        env::var("TOKEN").expect("TOKEN must be set!"),
    );

let mut headers: HeaderMap = HeaderMap::new();
        headers.insert(
            AUTHORIZATION,
            HeaderValue::from_static(&format!("Bearer {}", token)),
        );

I don't think I even need the String::from, but I was hoping that would copy the string, rather than borrow it from env::var.

The compiler is returning this error:

temporary value dropped while borrowed
creates a temporary value which is freed while still in use

for &format!("Bearer {}", token) which, to my understanding, is because the String needs to be static. Without using a library like lazy_static, is there a way I can better do this?


Solution

  • HeaderValue implements TryFrom<String>, so you can convert it with try_into.

    headers.insert(
        AUTHORIZATION,
        format!("Bearer {}", token).try_into().expect("invalid characters"),
    );
    

    You could make it static with, for example, OnceLock, but that shouldn't be necessary unless you are creating this HeaderMap multiple times.