How to convert String to &'static str in Rust?
Hi everyone, I just started learning Rust and already encountered a problem related to lifetimes. I have a function that returns &'static str, but I get a String from user input (via stdin) or from some other dynamic operation. How do I convert a regular String to &'static str?
Here's an example code that doesn't compile:
```rust
fn get_static_string(input: String) -> &'static str {
&input
}
fn main() {
let my_string = String::from("hello");
let static_str = get_static_string(my_string);
println!("{}", static_str);
}
```
The compiler gives an error: `cannot return reference to local variable 'input'`. I understand that this is because `input` will be destroyed after the function exits, but I need to return exactly `&'static
No answers yet.
Log in to leave an answer
Blogs