5 ms·
Thank you. The article made it sound to me like struct Foo<'c>, 'c is the lifetime of the struct. Am I correct in thinking that, in reality, 'c must live as lon
by groovy2shoes 11y ago
Thank you. The article made it sound to me like struct Foo<'c>, 'c is the lifetime of the struct. Am I correct in thinking that, in reality, 'c must live as long or outlive the struct?
- dbaupp 11y agoYeah, the lifetimes on a struct are the lifetimes of things that the struct points to, not an instance of the struct itself. For an instance to be valid, everything it points to must be valid, so if `foo: Foo<'c>`, `foo` cannot be stored for longer than `'c`. E.g. this code is invalid, because the `Foo` instance would live longer than the thing it points to: let foo = { let age = 0; Foo { age: &age } }; The `age` variable goes out of scope at the } (i.e. the maximum possible lifetime for &age ends there), and hence letting the `Foo` escape from that scope would be a bad idea. (NB. this applies to the "core" lifetime'd types like `&'c T` too: that is really just a nicer way to write a parameterised type like `Ref<'c, T>`. So the rule "cannot return a reference to a local variable" is the same rule that stops a `Foo<'c>` living too long.)
- groovy2shoes 11y agoMakes perfect sense. Thank you!
- Manishearth 11y agoThe article is wrong/misguided. See my comment above :) When you say `Foo<'c>`, all you're saying is that each `Foo` instance has an associated lifetime `'c`, similar to a type parameter. When you add the `x: &'c u8` field, then you're saying that "this lifetime is the lifetime of the inner u8". > Am I correct in thinking that, in reality, 'c must live as long or outlive the struct For the specific example, yes. It's possible to have an example where 'c must be shorter lived, and cannot outlive the struct. If you had an &mut instead of & there, then 'c must live exactly as long as the struct.
- groovy2shoes 11y agoThank you. > It's possible to have an example where 'c must be shorter lived, and cannot outlive the struct. I'm interested in such an example. Could you provide one?
- Manishearth 11y agoActually, I just looked into it, that's no longer possible. I was talking about contravariant lifetime positions, which happen with functions, but now it seems like function pointers are invariant in those positions, not contravariant. The idea was to have something like struct Foo<'a> {f: fn(&'a u8)} should only be able to accept pointers that live shorter than the struct. But contravariance seems to have been removed.
- groovy2shoes 11y agoMakes sense. I can see how having contravariant function arguments could produce some surprising behavior.