iTranslated by AI
Use String Instead of &str When Returning Strings from Functions in Rust
Motivation
When I started learning Rust, I noticed that String was used for string return values in every code I saw. To my 'fully Rust-understanding' self, I thought returning &str would be better.
Result
When using &str, the allocated memory is freed when exiting the function, so it's better to use String.
fn main() {
println!("{}", hello_world1());
//println!("{}", hello_world2()); // an "expected named lifetime parameter" error occurs
println!("{}", hello_world3());
}
fn hello_world1() -> String {
return "Hello world1".to_string();
}
// fn hello_world2() -> &str {
// return "Hello world2";
// }
fn hello_world3() -> &'static str {
return "Hello world3";
}
Supplement
Although it's possible to define it with &'static str, it seems the memory allocation method changes.
Variables with a static lifetime
The official documentation states the following:
By using a static lifetime, memory seems to be allocated for the entire duration of the program's execution. I don't think it's necessary to needlessly allocate memory for the entire program's execution just to return a string, so unless there's a compelling reason, using &'static str might be unnecessary.
Original Text
As a reference lifetime 'static indicates that the data pointed to by the reference lives for the entire lifetime of the running program. It can still be coerced to a shorter lifetime.
Discussion