删除已移动的值后,删除部分已移动的值 [英] Dropping partially moved values after the moved values are dropped

查看:74
本文介绍了删除已移动的值后,删除部分已移动的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I expect the following code to compile and print Foo(6) as the value of b, owning the reference to a is dropped after the match block.

似乎与此编译器错误有关:

It seems related to this compiler error:

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的值也不起作用,因为它已部分移动:

Dropping the value of b doesn't work either, because it is partially moved:

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行放入内部块更好的方法来解决此问题?看起来很丑陋.

Is there a better way to fix this rather than putting lines let b and match b into an inner block? That just looks wierd and ugly.

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

Shouldn't the compiler understand that the reference is dropped, and be able to compile that code?

#[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);
}

推荐答案

是否有更好的方法来解决此问题

Is there a better way to fix this

是的,但不是在稳定的Rust中.您需要非词法生存期:

Yes, but not in stable Rust. You need non-lexical lifetimes:

#![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() {}

在此之前,只需使用多余的方块即可.

Until then, just use the extra block.

删除b的值也不起作用

Dropping the value of b doesn't work either

drop与借贷无关.

另请参阅:

  • Moved variable still borrowing after calling `drop`?
  • What are the options to end a mutable borrow in Rust?
  • Why is a borrow still held in the else block of an if let?
  • Rust borrow of a HashMap lasts beyond the scope it's in?
  • How to end a borrow in a match or if let expression?
  • Borrow checker and function arguments in Rust, correct or over zealous?

这篇关于删除已移动的值后,删除部分已移动的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆