我有以下代码:

#[derive(Debug)]
pub enum List<'a> {
    Nil,
    Cons(i32, &'a List<'a>)
}

{
    let x = Cons(1, &Cons(2, &Nil));
    println!("{:?}", x);
}

它工作正常。我不明白为什么这段代码没有报告任何错误,在构建 Cons(2, &Nil) 之前不是删除了 Cons(1, _) 吗?

此外,在我为 impl Drop 添加一个空的 List 后,上面的代码不再起作用:
impl<'a> Drop for List<'a> {
    fn drop(&mut self) {

    }
}

它报告 borrowed value does not live long enoughCons(2, _)Nil 的错误。

为什么在添加 impl Drop 之前和之后会有这样的差异?

最佳答案



如果将引用绑定(bind)到临时对象,Rust 会根据绑定(bind)的需要延长临时对象的生命周期;有关详细信息,请参阅 this answer



this comment 。临时文件的延长生命周期与示例中 x 的生命周期相匹配。当包含引用的 struct 没有 Drop 实现时,

关于Rust 对临时值的引用不报告错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52884893/

10-12 06:54