nrc / r4cppp

Rust for C++ programmers

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Why would a reference dereference?

U007D opened this issue · comments

In Destructuring, you write

Lets say you want a reference to a variable in a pattern. You can't use & because that matches a reference, rather than creates one (and thus has the effect of dereferencing the object). For example, ...

  1. Do you mean a) "Let's say you want to make a reference to an (ordinary) struct field using a pattern (effectively aliasing the field)", b) "Let's say you want to refer to a reference variable in a struct using a pattern (creating an additional reference to the object referred to by the field)" or c) something else?

  2. Why would "matching a reference" have the effect of dereferencing the object? On the face of it, that is surprising behavior (unless it's to avoid a &&T (in which case I'd still have expected the dereference to yield the expected &T)). Maybe another sentence explaining why the dereference would be helpful?

  1. a

  2. There is nothing special about the match, it is about destructuring in patterns, e.g.,

let x = &&42;  // x: &&i32
let y = x; // y: &&i32
let &y = x; // y: &i32
let &&y = x; // y: i32
let ref y = x; // y: &&&i32
let y = &x; // y: &&&i32