1. 37

  2. 1

    Do we actually need ref?

    I’ve been wondering about this myself. Can anyone provide an intuitive explanation that goes beyond the official docs?

    1. 10

      Yes, we still need ref. In the context of patterns, ref adds a reference, while & matches a reference.

      let x = Some(42);
      let Some(ref y) = x; // y is now &42
      // let Some(&y) = x; <- fails to compile, because x is not a reference to anything
      let value = 42;
      let a = Some(&value);
      let Some(ref b) = a; // b is now &&42
      let Some(&c) = a; // c is now 42

      (note: the above code doesn’t actually compile, because rustc assumes there’s some way that x and a might possibly become None before the following lines, but that check happens in a phase after the one that gives problems for z)

      Since * is the dereference operator, you might expect * in a pattern to create a reference, but * is also the sigil for raw pointers (in the same way that & is the sigil for references) so that wouldn’t work.