矛盾的“缺少寿命说明符"表示为“否".拥有价值的错误 [英] Contradictory "missing lifetime specifier" error on owned value
问题描述
我编写了代码来对以下结构进行建模,其中一个节点引用了其父节点:
I wrote code to model the following structure, where a node has a reference to its parent node:
struct Node<'a> {
parent: &'a Node,
}
impl<'a> Node<'a> {
fn new(parent: &'a Node) -> Node {
Node { parent }
}
}
我认为,使用parent
属性上的lifetime参数和new
函数中的parent
参数时,很明显,引用parent
的值必须至少生存到拥有引用的子节点.
I thought with the lifetime parameter on the parent
attribute and on the parent
parameter in the new
function it is made clear that the value behind the reference to parent
has to live at least as long as the child node that holds the reference.
但是,编译器给了我两条"missing lifetime specifier
"消息.
However, the compiler gives me two "missing lifetime specifier
" messages.
error[E0106]: missing lifetime specifier
--> src/main.rs:2:17
|
7 | parent: &'a Node,
| ^^^^ expected lifetime parameter
该属性上的是个生存期参数.编译器在这里向我要什么?
There is a lifetime parameter on the attribute. What the hell does the compiler want from me here?
error[E0106]: missing lifetime specifier
--> src/main.rs:6:33
|
6 | fn new(parent: &'a Node) -> Node {
| ^^^^ expected lifetime parameter
在这里,我希望编译器假定返回值的生存期至少与'a
一样长.显然不是.我认为用生命周期参数注释拥有的值在语法上是不可能的(因为不必要).但是编译器似乎仍然希望在这里使用它,因此我给出了它所要的内容.
Here I expected the compiler to assume that the return value has to live at least as long as 'a
. Appearantly it does not. I thought it is syntactically impossible (because unnecessary) to annotate an owned value with a lifetime parameter. But still the compiler seemed to desire one here so I gave what it was asking for.
// --snip
fn new(parent: &'a Node) -> 'a Node {
// --snip
当我尝试编译它时,第二个错误变成了另一个错误:
When I tried to compile that, the second error turned into a differnt one:
error: expected type, found `'a`
--> src/main.rs:6:33
|
6 | fn new(parent: &'a Node) -> 'a Node {
| ^^
因此,现在编译器告诉我,这里不希望使用生命周期参数,这似乎与之前的消息矛盾.
如何在节点引用其父节点(其寿命至少与子节点本身一样长)的情况下正确表达此结构? Rc
是否只能使用,如果可以,为什么?
So now the compiler tells me that it doesn't expect a lifetime parameter here, which seems contradictory to the message from before.
How can I express this structure correctly, where a Node has a reference to its parent, which lives at least as long as the child node itself? Is it only possible with Rc
and if yes, why?
推荐答案
您对节点的定义是
struct Node<'a>
,但是以后您将不再提供该生命.您的new
签名必须看起来像
but later on you don't provide that lifetime anymore. Your new
signature must look like
fn new(parent: &'a Node) -> Node<'a>;
与您的结构定义相同
struct Node<'a> {
parent: &'a Node<'a>,
}
这篇关于矛盾的“缺少寿命说明符"表示为“否".拥有价值的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!