Rust 我能把这些生命中的任何一个暗示出来吗?

Rust 我能把这些生命中的任何一个暗示出来吗?,rust,Rust,我很难在阅读执行过程中不因疲劳而晕倒 您可以这样编写实现: struct HasLifetimes<'first, 'second> { sister: &'first i32, brother: &'second i32, } impl HasLifetimes<'_, '_> { fn new() -> Self { Self { sister: &101, brother: &10 }

我很难在阅读执行过程中不因疲劳而晕倒


您可以这样编写实现:

struct HasLifetimes<'first, 'second> {
    sister: &'first i32,
    brother: &'second i32,
}

impl HasLifetimes<'_, '_> {
    fn new() -> Self { 
        Self { sister: &101, brother: &10 }
    }
}


struct HasStruct<'first, 'second> {
    child: HasLifetimes<'first, 'second>,
    nephew: i32,
}

impl HasStruct<'_, '_> {
    fn new() -> Self {
        Self { child: HasLifetimes::new(), nephew: 1 }
    }
}

凉的我假设trait实现不可能实现同样的功能,或者您可能已经提到了?不可能,因为您必须指定两个结构中的生命周期是相同的。否则,就会出现借用检查器问题。@PabloTatoRamos对于许多用例,您可以使“第一个”和“第二个”的生命周期相同,这将进一步简化代码。@SvenMarnach当然,但这里不是这样
struct HasLifetimes<'first, 'second> {
    sister: &'first i32,
    brother: &'second i32,
}

impl HasLifetimes<'_, '_> {
    fn new() -> Self { 
        Self { sister: &101, brother: &10 }
    }
}


struct HasStruct<'first, 'second> {
    child: HasLifetimes<'first, 'second>,
    nephew: i32,
}

impl HasStruct<'_, '_> {
    fn new() -> Self {
        Self { child: HasLifetimes::new(), nephew: 1 }
    }
}