Struct needs a lifetime because?

僤鯓⒐⒋嵵緔 提交于 2019-12-01 21:37:15
Matthieu M.

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!