Skip to content

Cannot match on reference in slice pattern #55175

Closed
@sunjay

Description

@sunjay

Here's a minimal reproduction: (Rust Playground)

fn main() {
    let x = vec![1i32];
    let value: i32 = match &x[..] {
        [&v] => v,
        _ => panic!(),
    };
}

Since the type of &x[..] is &[i32], I expect its contents to be &i32 (or else we would move unexpectedly). However, trying to match on that reference to force a copy here does not work because the error message indicates that the type of v inside the pattern is in fact i32, not &i32.

error[E0308]: mismatched types
 --> src/main.rs:4:10
  |
4 |         [&v] => v,
  |          ^^ expected i32, found reference
  |
  = note: expected type `i32`
             found type `&_`
  = help: did you mean `v: &i32`?

Note: If you noticed the weird help message, I filed an issue for that already: #55174

This is further complicated by the fact that if you remove the & from v (since it's type is i32 right??), it still doesn't work because the type of v is actually &i32 like I originally expected.

error[E0308]: match arms have incompatible types
 --> src/main.rs:3:22
  |
3 |       let value: i32 = match &x[..] {
  |  ______________________^
4 | |         [v] => v,
  | |                - match arm with an incompatible type
5 | |         _ => panic!(),
6 | |     };
  | |_____^ expected i32, found &i32
  |
  = note: expected type `i32`
             found type `&i32`

Both the type of v in the pattern and the type of v on that is returned into value should probably be the same.

Could this be a weird interaction with the match ergonomics features added recently?

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-slice-patternsArea: Slice patterns, https://github.com/rust-lang/rust/issues/23121T-langRelevant to the language team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions