3

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Jal
  • 2,174
  • 1
  • 18
  • 37
  • I believe your question is answered by the answers of [How does the lifetime work on constant strings?](https://stackoverflow.com/q/31230585/155423). If you disagree, please [edit] your question to explain the differences. Otherwise, we can mark this question as already answered (and delete my answer). – Shepmaster May 16 '18 at 01:10
  • Is the `return &s` in `return_string1` equivalent to `return s` because `&s` is auto-derefed? I was kind of expecting that to be a type error. – sepp2k May 16 '18 at 01:27
  • 2
    @sepp2k yes, it's [automatically dereferenced](https://stackoverflow.com/q/28519997/155423) because return values are a [coercion site](https://doc.rust-lang.org/nomicon/coercions.html). – Shepmaster May 16 '18 at 01:29
  • @shepmaster Thanks. I feel like there should be a warning if an address-of expression is immediately auto-derefed. Something like "Warning: Redundant `&`". I think that might have prevented OP's confusion in this case. – sepp2k May 16 '18 at 01:45
  • @sepp2k Clippy warns on that for a function argument, not sure why it doesn't for a return value. – Shepmaster May 16 '18 at 01:48

0 Answers0