解构一盒对时附带移动错误 [英] Collaterally moved error when deconstructing a Box of pairs

查看:25
本文介绍了解构一盒对时附带移动错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下两行:

let x = Box::new(("slefj".to_string(), "a".to_string()));
let (a, b) = *x;

产生错误:

error[E0382]: use of moved value: `x`
 --> src/main.rs:3:13
  |
3 |     let (a, b) = *x;
  |          -  ^ value used here after move
  |          |
  |          value moved here
  |
  = note: move occurs because `x.0` has type `std::string::String`, which does not implement the `Copy` trait

有趣的是,如果我使用具有多个部分的枚举类型来执行此操作,则会得到一个略有不同的错误:

Interestingly, if I do this with an enumeration type with multiple parts, I get a slightly different error:

enum Tree {
    Nil,
    Pair(Box<Tree>, Box<Tree>),
}

fn main() {
    let x = Box::new(Tree::Nil);

    match *x {
        Tree::Pair(a, b) => Tree::Pair(a, b),
        _ => Tree::Nil,
    };
}

我收到错误:

error[E0382]: use of collaterally moved value: `(x:Tree::Pair).1`
  --> src/main.rs:10:23
   |
10 |         Tree::Pair(a, b) => Tree::Pair(a, b),
   |                    -  ^ value used here after move
   |                    |
   |                    value moved here
   |
   = note: move occurs because `(x:Tree::Pair).0` has type `std::boxed::Box<Tree>`, which does not implement the `Copy` trait

为什么会发生这种情况,我如何使用 let/match 轻松破坏结构并获得内部部件的所有权?我知道我可以先取消引用并命名结构,但是如果我在结构中进行模式匹配,那会变得非常冗长.

Why does this happen, and how can I easily destruct structures with let/match and get ownership of the inner parts? I know I can dereference and name the structure first, but that gets horribly verbose if I'm pattern matching deep into a structure.

推荐答案

您偶然发现了一个 对解构和盒子的限制.幸运的是,解决这些问题很容易.您需要做的就是引入一个包含整个结构的新中间变量,并从中解构:

You have stumbled on a limitation on destructuring and boxes. Luckily, it's easy to work around these. All you need to do is introduce a new intermediary variable that contains the whole structure, and destructure from that:

let x = Box::new(("slefj".to_string(), "a".to_string()));
let pair = *x;
let (a, b) = pair;

第二个例子:

let pair = *x;
match pair {
    Tree::Pair(a, b) => Tree::Pair(a, b),
    _ => Tree::Nil,
};

这篇关于解构一盒对时附带移动错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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