rust-lang/rust

somewhat surprising match default binding interaction

nikomatsakis opened this issue · 2 comments

It took me a while to figure out the compilation error in this example (try it yourself):

#![feature(match_default_bindings)]

fn surprise(x: i32) { }

fn main() {
  let x = &(1, &2);
  let (_, &b) = x;
  surprise(b);
}

Here you get:

error[E0308]: mismatched types
 --> src/main.rs:9:12
  |
9 |   surprise(b);
  |            ^
  |            |
  |            expected i32, found &{integer}
  |            help: consider dereferencing the borrow: `*b`
  |
  = note: expected type `i32`
             found type `&{integer}`

Naturally I tried changing the pattern &&b. That gives you:

error[E0308]: mismatched types
 --> src/main.rs:7:12
  |
7 |   let (_, &&b) = x;
  |            ^^ expected integral variable, found reference
  |
  = note: expected type `{integer}`
             found type `&_`
  = help: did you mean `b: &{integer}`?

What the heck?

What's going on here is that the filter is giving us an &(i32, &i32). When we skip the first &, we get into "ref by default" mode, but when we explicitly acknowledge the second one, we do not get back into "by value" mode. That's kind of annoying.

durka commented

To check my understanding, the #![feature(match_default_bindings)] turns (_, &b) into &(_, &ref b)?

effectively yes