【问题标题】:Dropping partially moved values after the moved values are dropped在删除移动的值后删除部分移动的值
【发布时间】:2018-09-05 01:17:47
【问题描述】:

我希望下面的代码编译并打印Foo(6) 作为b 的值,拥有对a 的引用在匹配块之后被删除。

似乎与这个编译器错误有关:

error[E0502]: cannot borrow `a` as immutable because it is also borrowed as mutable
  --> src/main.rs:26:22
   |
13 |     let b = get_foo(&mut a);
   |                          - mutable borrow occurs here
...
26 |     println!("{:?}", a);
   |                      ^ immutable borrow occurs here
27 | }
   | - mutable borrow ends here

删除b 的值也不起作用,因为它被部分移动了:

error[E0382]: use of partially moved value: `b`
  --> src/main.rs:24:10
   |
18 |         Some(value) => *value = y,
   |              ----- value moved here
...
24 |     drop(b);
   |          ^ value used here after move
   |
   = note: move occurs because `(b:std::prelude::v1::Some).0` has type `&mut u32`, which does not implement the `Copy` trait

有没有更好的方法来解决这个问题,而不是将行 let bmatch b 放入内部块中?这看起来很奇怪和丑陋。

编译器不应该理解引用被删除,并且能够编译该代码吗?

#[derive(Debug)]
struct Foo(u32);

fn get_foo(bar: &mut Foo) -> Option<&mut u32> {
    Some(&mut bar.0)
}

pub fn test() {
    let mut x = 5;
    let mut y = 6;
    let mut a = Foo(x);

    // {
    
    let b = get_foo(&mut a);

    match b {
        Some(value) => *value = y,
        _ => (),
    }
    
    // }

    //    drop(b);

    println!("{:?}", a);
}

【问题讨论】:

    标签: compiler-errors rust lifetime


    【解决方案1】:

    有没有更好的方法来解决这个问题

    是的,但不是稳定的 Rust。您需要非词法生命周期

    #![feature(nll)]
    
    #[derive(Debug)]
    struct Foo(u32);
    
    fn get_foo(bar: &mut Foo) -> Option<&mut u32> {
        Some(&mut bar.0)
    }
    
    pub fn test() {
        let x = 5;
        let y = 6;
        let mut a = Foo(x);
    
        let b = get_foo(&mut a);
    
        if let Some(value) = b {
            *value = y;
        }
    
        println!("{:?}", a);
    }
    
    fn main() {}
    

    在那之前,只需使用额外的块。

    删除 b 的值也不起作用

    drop 与借用无关。

    另见:

    【讨论】:

    • 为什么下降与此无关?据我了解,编译器抱怨b 是/可能持有a 的引用。删除b 应该会解决这个问题,不是吗? NLL 会处理它,我应该仔细阅读它到底是什么,但我也对 drop 的问题感兴趣。
    • @ÁkosVandra 如果您对我链接到的第一个问题 (Moved variable still borrowing after calling drop?) 有不明白的地方,也许添加 cmets 会更合适。
    猜你喜欢
    • 2014-01-31
    • 2021-03-01
    • 2018-11-11
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    • 1970-01-01
    • 2016-06-09
    • 2017-05-19
    相关资源
    最近更新 更多