Convert string::String to &'static str


#1

Hi,

I have a library function which returns std::string::String, but I need to store it in &'static str variable, how can I do this? The reason of this conversion is that, the variable is defined in a structure and is of type &'static str.

I defined the variable as &'static str because I found it easier to copy the structure using #[derive(Clone, Copy)]

and how can I define the copy for the structure containing std:string::String?

Which is better whether to change the struct element to String or to convert str to String?

Please let me know,
Thank you and regards


#2

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>.


#3

std::mem::forget is not unsafe.


#4

Sure, but you still can’t safely get a &'static str out of the String before forgetting it.