为什么& str没有"活得不够长"从函数返回时出现问题?

时间:2018-05-16 00:55:51

标签: rust

请考虑以下代码:

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没有同样的问题?

0 个答案:

没有答案