结构需要一生,因为? [英] Struct needs a lifetime because?

查看:78
本文介绍了结构需要一生,因为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(每个标记有?的声明都希望声明)

(Every statement marked with ? wishes to be asserted)

我只是一辈子慢慢来.

由于生存期省略有助于省略对生存期的明确描述(?),因此在某些情况下需要对其进行描述.

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

示例可能是包含引用的结构:

An example might be a struct which holds a reference:

struct Person<a'>{
car: &'a Car
}

我对以下假设是正确的

一个结构是一个值类型-因此它的内存位于堆栈上.范围结束后,该结构将在其中使用-该结构将死亡.但是由于该结构包含对 Car 的引用,并且该引用可能会借用到其他地方-只要使用Car引用,该结构NEEDS就会保持有效.因此,生命周期'a 告诉Person结构只要汽车在使用中就可以存活.(?)

a struct is a value type - therefore its memory lies on the stack. After the scope ends where this struct is used in - the struct will die. 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. The Lifetime 'a therefore tells the Person struct to stay alive as long as Car is in use.(?)

说实话,我不相信上述声明.因为在防锈寿命的其他定义中,我理解的是-汽车至少需要保持'a 的寿命,这样Person才不会有悬空的指针.

to be honest I don't believe myself with this statement above. Because in other definitions of the rust lifetime I understood it so - that the Car needs to stay alive at least as long as 'a so Person won't have a dangling pointer.

推荐答案

由于生存期省略有助于省略对生存期的明确描述(?),因此在某些情况下,我们需要对其进行描述.

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

在这里没有 As ,一生的消除只是为了使您的生活更轻松(包括作家和读者).生命周期仍然存在(象征性地),但是不必明确地(在语法上)表示.

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).

终身省略在struct定义中不起作用.它可以在函数签名和主体中使用.

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

但是由于此结构包含对Car的引用,并且该引用可能会借用到其他地方-只要使用Car引用,该结构NEEDS即可保持活动状态.

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.

  • 悬挂引用是引用(长)死值的引用,可能在释放的内存中,或者在(更糟的)重用内存中.
  • 借入检查器使用借入关系来跟踪某人是否仍具有对值的引用;当某人拥有对值的引用时,不应将其移动或更改为其他类型,以免引用变得悬而未决.

有关悬空引用的详细说明,请推荐这个问题.

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.

因此,约束与您的信念相反:'a的目标是让编译器确保您的Person永不超过其引用的Car.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆