我刚刚开始学习来自Java/JavaScript背景的Rust,所以请耐心等待,因为我明显错过了我对生命时间的理解。我在生命中缺少什么?
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的问题相同。 –
另一方面,由于这些值按照与它们声明相反的顺序被删除,所以也可以通过交换顺序来解决这个问题,即使用'other_appearance == appearance'而不是'appearance == other_appearance'。是的,Rust有几个疣子... –
谢谢!我需要详细说明语法,即使我在概念上理解你所说的:) –