Rust: 不能在没有中间 let 绑定的情况下解构盒装结构

创建于 2018-01-12  ·  3评论  ·  资料来源: rust-lang/rust

此代码无法编译:

struct Foo;

struct Bar {
    a: Foo,
    b: Foo,
}

fn main() {
    let bar = Box::new(Bar { a: Foo, b: Foo });

    let Bar { a, b } = *bar;
}
error[E0382]: use of moved value: `bar`
  --> x.rs:11:18
   |
11 |     let Bar { a, b } = *bar;
   |               -  ^ value used here after move
   |               |
   |               value moved here
   |
   = note: move occurs because `bar.a` has type `Foo`, which does not implement the `Copy` trait

然而,在盒子 deref 和解构之间插入一个中间 let 绑定可以修复它:

fn main() {
    let bar = Box::new(Bar { a: Foo, b: Foo });

    let Bar { a, b } = { let intermediate = *bar; intermediate };
}

这感觉像一个错误。

受影响的版本:

  • rustc 1.23.0 (766bd11c8 2018-01-01)

  • rustc 1.25.0-nightly (73ac5d6a8 2018-01-11)

C-bug T-compiler

最有用的评论

盒子图案也会发生。

#![feature(box_patterns)]

struct Foo;

struct Bar {
    a: Foo,
    b: Foo,
}

fn main() {
    let bar = Box::new(Bar { a: Foo, b: Foo });

    let box Bar { a, b } = bar;
}

所有3条评论

盒子图案也会发生。

#![feature(box_patterns)]

struct Foo;

struct Bar {
    a: Foo,
    b: Foo,
}

fn main() {
    let bar = Box::new(Bar { a: Foo, b: Foo });

    let box Bar { a, b } = bar;
}

分类:这是固定的!

此页面是否有帮助?
0 / 5 - 0 等级