rust - 如何在不调用克隆的情况下将多个值移出装箱值?

标签 rust

<分区>

我有一个盒装元组来避免递归。但是,当我对元组进行模式匹配时,我似乎无法同时获得两个元组值。为了说明我的问题,取 the following code :

#[derive(Clone, PartialEq, Debug)]
enum Foo {
    Base,
    Branch(Box<(Foo, Foo)>),
}

fn do_something(f: Foo) -> Foo {
    match f {
        Foo::Base => Foo::Base,
        Foo::Branch(pair) => {
            let (f1, f2) = *pair;
            if f2 == Foo::Base {
                f1
            } else {
                f2
            }
        }
    }
}

fn main() {
    let f = Foo::Branch(Box::new((Foo::Base, Foo::Base)));
    println!("{:?}", do_something(f));
}

我收到这个错误:

error[E0382]: use of moved value: `pair`
  --> src/main.rs:11:22
   |
11 |             let (f1, f2) = *pair;
   |                  --  ^^ value used here after move
   |                  |
   |                  value moved here
   |
   = note: move occurs because `pair.0` has type `Foo`, which does not implement the `Copy` trait

我读过有关盒装语法的内容,但我想尽可能避免使用不稳定的功能。感觉唯一的答案是将 Branch 重新定义为

Branch(Box<Foo>, Box<Foo>)

但这似乎避免了回答问题(目前公认这主要是一种思考练习)。

最佳答案

这是在 non-lexical lifetimes 时修复的被介绍。原始代码现在按原样编译:

#[derive(Clone, PartialEq, Debug)]
enum Foo {
    Base,
    Branch(Box<(Foo, Foo)>),
}

fn do_something(f: Foo) -> Foo {
    match f {
        Foo::Base => Foo::Base,
        Foo::Branch(pair) => {
            let (f1, f2) = *pair;
            if f2 == Foo::Base {
                f1
            } else {
                f2
            }
        }
    }
}

fn main() {
    let f = Foo::Branch(Box::new((Foo::Base, Foo::Base)));
    println!("{:?}", do_something(f));
}

这是在 issue 16223 中跟踪的.

关于rust - 如何在不调用克隆的情况下将多个值移出装箱值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34256165/

相关文章:

rust - 通过取消引用来延长对象的生命周期

rust - Rust 的内置目标规范在哪里定义?

rust - Rust 可以在没有垃圾收集器的情况下处理循环数据结构吗?

rust - 可以在 Rust 中推断数组长度吗?

rust - 什么时候创建临时值?

string - 我如何在 Rust (crossbeam) 中与多个生产者和一个接收者共享字符串消息?

random - 如何在 Rust 1.0 中获取随机数?

macros - rustc --pretty Expanded 在解析外部 block 内的宏扩展时使用我的所有 RAM

rust - 如何创建以特征作为参数的setter

syntax - 如何编写更通用的 IntoIter 函数