Skip to content

By-reference pattern guards #2036

Closed
Closed
@the8472

Description

@the8472
    match Some(vec![1]) {
        Some(v) if !v.is_empty() => { v.into_boxed_slice(); },
        _ => { vec![0; 0].into_boxed_slice(); }
    }

errors with

error[E0008]: cannot bind by-move into a pattern guard
 --> <anon>:3:14
  |
3 |         Some(v) if !v.is_empty() => { v.into_boxed_slice(); },
  |              ^ moves value into pattern guard

The usual workaround is to use Some(ref v) instead. But this prevents the match block from taking ownership.

This forces the guard to be moved into the match, which leads to duplicate code A and B:

    match Some(vec![1]) {
        Some(v) => {
            if !v.is_empty() {
                v.into_boxed_slice(); 
            } else {
                vec![0; 0].into_boxed_slice(); // A
            }
        },
        _ => {
            vec![0; 0].into_boxed_slice(); // B
        }
    }

It would be more ergonomic if moving match arms with guards passed their values by reference to the guard.

Metadata

Metadata

Assignees

No one assigned

    Labels

    T-langRelevant to the language team, which will review and decide on the RFC.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions