我刚开始学习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);
}
当编译器到达other_appearance
时,我遇到了编译错误,告诉我another_thing
没有足够长的生命周期。然而,如果我省略创建other_appearance
,程序就可以编译和运行正常。为什么会出现这个错误?
#[derive(PartialEq)]
创建的实例与OP的问题相同。 - Peter Hallother_appearance == appearance
而不是appearance == other_appearance
。是的,Rust 有一些缺陷... - Peter Hall