请考虑以下代码:
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
会遇到问题:
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 | | }
| |_^
这是令人惊讶的,因为我期望return_string1
会遇到同样的问题,因为s
在函数堆栈中被分配,并且在函数返回后将被删除。
为什么return_string1
没有同样的问题?