Rust 生锈寿命问题:impl使用匿名寿命,函数使用<';a>;,更改生存期以匹配将导致错误

Rust 生锈寿命问题:impl使用匿名寿命,函数使用<';a>;,更改生存期以匹配将导致错误,rust,lifetime,Rust,Lifetime,您可以运行代码段。我删除了一堆与结构无关的函数和字段,以简化分析 #[derive(Debug)] pub struct Turtle<'a>{ children: Vec<&'a Turtle<'a>>, } impl Turtle<'_>{ pub fn new() -> Turtle<'static> { Turtle {children: Vec::new()} }

您可以运行代码段。我删除了一堆与结构无关的函数和字段,以简化分析

#[derive(Debug)]
pub struct Turtle<'a>{
    children: Vec<&'a Turtle<'a>>,
}

impl Turtle<'_>{
    pub fn new() -> Turtle<'static> {
        Turtle {children: Vec::new()}
    }
    pub fn add_child<'a>(&self, t: &'a Turtle<'a>) {
        &self.children.push(t);
    }
}
#[派生(调试)]
乌龟{
pub fn new()->海龟(&self,t:&'a海龟`
找到了参考`&src/lib.rs:10:22
|
10 | pub fn add_child src/lib.rs:6:13
|

6 | impl-Turtle,因此self.children具有匿名生存期,这意味着push期望一个Turtle或参数t的生存期您的结构需要一个生存期,您选择将其称为“a”。然后,该生存期将“给予”self.children或“与self.children共享”。稍后,您将为匿名生存期(即生命)实现结构结构定义声明self.children也必须共享的时间。但是,您的“new”函数意味着创建具有“static”生存期的self.children(并且“static!=”\uAs'\uuu可能比“static”短)。此外,您的add child方法需要一个(合理地)完全独立的生存期,您也可以将其称为“a”(仅仅因为您称其为“a”并不意味着它与您在结构定义中命名的“a”相同)。请尝试创建一个采用类型而不是使用生存期(例如T或V)的新结构?如果两者都没有边界,则它们本质上是相等的。这同样适用于生存期

实际的解决方案在于匹配你的生命周期。因为你的结构的自引用性质,你不能使用匿名生命周期,因为编译器需要知道在添加子代时的生命期匹配。下面是编译的内容。请注意使用自我推断生命周期,但我个人会考虑使用自易性,因为它避免了额外的生存期引用。另外,为了使add_child方法能够工作,对“self”的引用需要是可变的(请参见&mut self)。这是因为您正在修改self.children的内容,因此会改变结构

请注意,这将适用于“任意”生存期,无论您是否将其称为“a”或“z”或其他任何名称。关键是编译器可以推断出所涉及的所有内容的生存期都是匹配的

    #[derive(Debug)]
    pub struct Turtle<'a> {
        children: Vec<&'a Turtle<'a>>,
    }

    impl<'a> Turtle<'a> {
        pub fn new() -> Self {
            Self { children: Vec::new() }
        }

        pub fn add_child(&mut self, t: &'a Turtle<'a>) {
            self.children.push(t);
        }
    }
#[派生(调试)]

pub struct Turtle你可以有两个
impl
s:@ForceBru我希望有一个包含所有函数的impl,比如add_child和我遗漏的任何函数。你的想法现在可行,但当我开始向impl添加函数时,我会遇到各种新错误。这是你的意思吗?它不起作用,编译器会问让我重新添加“static to new()。抱歉,它确实稍微复杂一些。已更新。
    #[derive(Debug)]
    pub struct Turtle<'a> {
        children: Vec<&'a Turtle<'a>>,
    }

    impl<'a> Turtle<'a> {
        pub fn new() -> Self {
            Self { children: Vec::new() }
        }

        pub fn add_child(&mut self, t: &'a Turtle<'a>) {
            self.children.push(t);
        }
    }