Skip to content

2021 edition's binding to sub-pattern doesn't work on enum with copyable fields #90368

@detly

Description

@detly

I tried the new "binding to sub-patterns" feature in the 2021 edition and it did not work as I expected, or consistently. Here's a playground link.

First, I tried:

// NOT copy!
#[derive(Debug)]
enum One {
    A,
    B(bool),
}

fn main() {
    let a = One::B(true);
    
    match a {
        One::A => println!("A"),
        other @ One::B(success) => {
            println!("{:?}", other);
            println!("{}", success);
        }
    }
}

I expected that even though the wrapping enum is not Copy, because the nested bool value is, it would be copied into success. However, I get the error:

error[E0382]: use of moved value: `a`
  --> src/main.rs:13:24
   |
9  |     let a = One::B(true);
   |         - move occurs because `a` has type `One`, which does not implement the `Copy` trait
...
13 |         other @ One::B(success) => {
   |         ---------------^^^^^^^-
   |         |              |
   |         |              value used here after move
   |         value moved here

For more information about this error, try `rustc --explain E0382`.
error: could not compile `playground` due to previous error

Comparing this to the example in the release notes, where there's a non-Copy container (Matrix) with a Copy-able field (row_len), I don't see why it shouldn't work the same way.

Strangely (I think), if I remove the A variant, it works. So infallible patterns allow this.

It will also work if I do ref other @ One::B(success), but then I can't take ownership of other.

Rust version: rustc 1.56.0 (09c42c458 2021-10-18)
Platform: Ubuntu 21.04
Installed via Rustup

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-borrow-checkerArea: The borrow checkerA-patternsRelating to patterns and pattern matchingC-bugCategory: This is a bug.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions