Fix error[E0080]: runtime values cannot be referenced in patterns

As per what I stumbled into (despite being somewhat experienced) this

match x {
    ..y => smaller,
    y   => equal,
    _   => greater
}

is ambiguous and thus a beginner’s trap: does y want to capture something (not possible in the 1st branch) or be an outer variable? Despite the limitation that ranges can’t capture like this, Rust has chosen variable names in patterns to mean capturing. This makes it syntactically impossible to pass in dynamic values.

Leaving aside that dynamic branches might not optimize as well as compile time known branches, I find them very desirable. Since one syntax can’t have it both ways, my idea is to use block expressions to disambiguate them. Here y would clearly be an outer variable:

match x {
    ..{y} => smaller,
    {y}   => equal,
    _     => greater
}

And since the range branch isn’t actually ambiguous, a block may not be deemed necessary there.

4 Likes

This is a trap indeed. Unfortunately, existence of an alternative syntax won't stop people from falling into the trap of the easy syntax.

The pitfall could be better fixed with an explicit warning. Currently there are warnings about potentially unused variables and redundant match arms, but the compiler could detect the mistake more directly.

1 Like