Struct needs a lifetime because?

前端 未结 2 1224
花落未央
花落未央 2021-01-20 18:04

(Every statement marked with ? wishes to be asserted)

I\'m just coming along with lifetimes slowly.

As lifetime elision helps to om

相关标签:
2条回答
  • 2021-01-20 18:32

    It's the other way around: The struct contains a reference, thus it may not outlive the thing the reference points to.

    0 讨论(0)
  • 2021-01-20 18:54

    As lifetime elision helps to omit explicitly describing a lifetime (?) there are cases where we need to describe them.

    No As here, lifetime elision is simply about making your life easier (both as writer and reader). The lifetimes are still present (semantically) but need not be explicitly denoted (syntactically).

    Lifetime elision does not work in struct definition, as far as I know. It works in functions signatures and bodies.

    But since this struct holds a reference to a Car and this reference might be borrowed to somewhere else - the struct NEEDS to stay alive as long as the Car reference is in use.

    No. The goal of lifetime is to avoid dangling references, and indicate borrowing relationships.

    • Dangling references are references that refer to (long-)dead values, possibly in freed memory or (worse) in reused memory.
    • Borrowing relationships are used by the borrow checker to track whether someone still has a reference into a value or not; while someone has a reference into a value, it should not be moved or changed to another type lest said reference becomes dangling.

    For a deeper explanation of dangling references, I recommend this question.

    Therefore, lifetimes are about ensuring that a reference NEVER outlives the value it refers to.

    The constraint, therefore, is the opposite of your belief: the goal of 'a here is to let the compiler ensure that your Person never outlives the Car it refers to.

    0 讨论(0)
提交回复
热议问题