Consider the following code:
fn return_string1(filename: &str) -> &str {
let s = "hi";
return &s;
}
fn return_string2(filename: &str) -> &String {
let s = String::from("Hello, Rust!");
return &s;
}
return_string2
will encounter a problem:
error[E0597]: `s` does not live long enough
--> src/main.rs:8:13
|
8 | return &s;
| ^ borrowed value does not live long enough
9 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the anonymous lifetime #1 defined on the function body at 6:1...
--> src/main.rs:6:1
|
6 | / fn return_string2(filename: &str) -> &String {
7 | | let s = String::from("Hello, Rust!");
8 | | return &s;
9 | | }
| |_^
This is surprising since I expect return_string1
will encounter the same problem since s
is allocated in the function's stack and will be dropped after the function returns.
Why does return_string1
not have the same issue?