Convert string::String to &'static str

You can't convert a String into &'static str safely - &'static means a reference that lives for the entire duration of the program, while the String could get destroyed at any time, when it leaves a scope. (You could make Rust forget the string, which would effectively ensure the slice reference lives on, but that's neither possible in safe Rust nor intended.)

You have two choices: let the struct own the String, or add a non-static lifetime to the reference. In the former case, your struct isn't Copy anymore, but if you're copying it a lot, you should check if that is necessary, or if you could pass references to it around instead.

A third possibility, for the case that the struct sometimes contains legitimate &'static references, is to use Cow<'static, str>.

1 Like