Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

  // this function foo
  fn foo(s: &str) -> &str {
      &s[0..1]
  }
  
  // is equivalent to this function
  fn foo_desugared<'a>(s: &'a str) -> &'a str {
      &s[0..1]
  }
  
  // this works too because the lifetime of "" is 'static because
  // it is a str that lives in the .data segment, which will live for "any 'a"
  fn bar(s: &str) -> &str {
      &""
  }
  
  fn main() {
      // as shown here
      bar(&String::new());
  }
  
  // but this won't work, because `x` gets `drop`ed at the end of `baz`
  fn baz(x: &str) -> &str {
      let x = String::new();
      &x
  }
https://play.rust-lang.org/?version=stable&mode=debug&editio...

Keep in mind that lifetimes have the opposite behavior of generic types. A T: Trait type parameter means "something that implements at least Trait, but might implement other things that you won't have access to", while an &'a returned borrow means "something that lives at least up to 'a, but might live less".



>Keep in mind that lifetimes have the opposite behavior of generic types. A T: Trait type parameter means "something that implements at least Trait, but might implement other things that you won't have access to", while an &'a returned borrow means "something that lives at least up to 'a, but might live less".

I don't know what you're trying to say here, but taken at face value it is wrong, and your own `fn bar` example demonstrates it being wrong. "something that lives at least up to 'a but might live less" is a contradiction.

Perhaps you meant "... but might live longer" ? If so, it would be correct, and also would not be "the opposite behavior of generic types."


Given

  fn foo(x: &str) -> &str {
      x
  }
calling `let z = foo(y);` is valid. The lifetime of `y` conforms to the lifetime of `x` in the `foo` signature, while the lifetime of `z` can be as long as the one for `x` (up to x's lifetime), but it is shorter (unless you try to do `drop(y)`, which would be a borrow checker error).


Okay, so you were talking about it from the POV of the caller, not the function. In that case, you meant "at most", not "at least". That is:

>while an &'a returned borrow means "something that lives at most up to 'a, but might live less".




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: