Correct way to return a new string from a function in Rust
Hello! I'm new to Rust and trying to figure out returning strings from functions. In other languages, I would just create a string and return it, but in Rust it's more complicated due to the ownership system.
I have a function that should take a string, add a prefix to it, and return a new string. Here's my code that doesn't work:
```rust
fn add_prefix(s: &str) -> &str {
let result = String::from("prefix_") + s;
&result
}
```
The compiler gives an error: `cannot return reference to local variable 'result'`. I understand that `result` is dropped after exiting the function, but how do I correctly return a new string?
I've tried different options:
1. Returning `String` instead of `&str` — but then in the calling code I need to borrow the string again.
2. Using `to_string()` — but this seems
No answers yet.
Log in to leave an answer