Avatar ·

How to return a reference to a variable created inside a function in Rust?

Hi everyone! I just started learning Rust and encountered a problem that I can't solve. I'm writing a function that creates a String inside itself, processes it, and then wants to return a reference to this string. Here's simplified code: ```rust fn get_data() -> &str { let data = String::from("Hello, world!"); &data } ``` The compiler gives an error: `cannot return reference to local variable 'data'`. I understand that this is related to lifetimes, but I don't fully grasp the essence. In C++ I could return a pointer to a local array (even though it's UB), and in Python there's no such problem at all. How do I correctly return a reference to a string created inside a function? I need the function to return exactly &str, not String, because later I will pass it to other functions,