避免悬垂引用

  1. {
  2. let r;
  3. {
  4. let x = 5;
  5. r = &x;
  6. }
  7. println!("r: {}", r);
  8. }
  1. fn longest(x: &str, y: &str) -> &str {
  2. if x.len() > y.len() {
  3. x
  4. } else {
  5. y
  6. }
  7. }
  1. --> src\main.rs:6:33
  2. |
  3. 6 | fn longest(x: &str, y: &str) -> &str {
  4. | ^ expected lifetime parameter
  5. |
  6. = help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `x` or `y`
  1. fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
  2. if x.len() > y.len() {
  3. x
  4. } else {
  5. y
  6. }
  7. }