在生命中,我是否遗漏了一些东西?

Lar*_*äck 2 rust

我刚开始学习Rust,来自Java/JavaScript背景,所以请耐心等待,因为我对生命时间的理解显然缺少一些东西.

fn main() {
    struct Appearance<'a> {
        identity:       &'a u64, 
        role:           &'a str
    };
    impl<'a> PartialEq for Appearance<'a> {
        fn eq(&self, other: &Appearance) -> bool {
            self.identity == other.identity && self.role == other.role
        }
    };
    let thing = 42u64;
    let hair_color = "hair color";
    let appearance = Appearance { 
        identity: &thing, 
        role: &hair_color 
    };
    let another_thing = 43u64;    
    let other_appearance = Appearance { 
        identity: &another_thing, 
        role: &hair_color 
    };
    println!("{}", appearance == other_appearance);
}
Run Code Online (Sandbox Code Playgroud)

当编译器到达时other_appearance,这给了我一个编译错误,告诉我another_thing没有足够长的时间.但是,如果我遗漏了other_appearance程序的创建编译并运行正常.为什么我收到此错误?

int*_*jay 5

该PartialEq特征具有一个类型参数,用于指定右侧的类型.由于您未指定它,因此默认为与左侧相同的类型.这意味着假设双方的生命周期相同.这会导致错误,因为another_thing之前会被删除appearance,但是other_appearance(保留another_thing对它的引用)被认为具有与之相同的生命周期appearance.

您可以通过在右侧使用不同的生命周期来解决此问题:

impl<'a, 'b> PartialEq<Appearance<'b>> for Appearance<'a> {
    fn eq(&self, other: &Appearance<'b>) -> bool {
        self.identity == other.identity && self.role == other.role
    }
};
Run Code Online (Sandbox Code Playgroud)