Borrow value from tuple/enum tuple

Hi. Hm, is there a reason why the destructuring pattern let V(&a) = ... is syntatically valid with&? I first thought it'd borrow a, but, differently, that & just indicates a is a reference type, i.e., a: &A. I needed it for borrowing a value from a enum variant for efficiency, but unfortunately...

Everything inside the pattern "reverses" the operation done inside an expression – for example, the V in an expression constructs an enum from a variant's payload, and inside the pattern, the V deconstructs it and allows access to the variant's payload. The & works similarly – in an expression it constructs a reference, and inside a pattern, it matches a reference (&T) and "unwraps" it, leaving just T, (so basically, it performs a dereference).

Actually, it means that the value inside V should be of type &A, but after the let, the a will have a type A. I think it's best to see an example that shows the symmetry:

let Enum::V(&x) = Enum::V(&5);
// x is now i32 of value 5

Seems that you need the ref keyword instead (alternatively pattern match ergonomics), but you should be able to google that or find more info in official docs :slight_smile:

1 Like