Mnemonic for reading qualifiers


#1

I thought I understood patterns, references and binding but this one from the docs (as_mut) totally left me flummoxed.

fn mutate(r: &mut Result<i32, i32>) { match r.as_mut() { Ok(&mut ref mut v) => *v = 42, Err(&mut ref mut e) => *e = 0, } }

How do we read qualifiers such as &mut ref mut v. Is there a useful mnemonic to read them. Also please explain why the order in which qualifiers appear is important.


#2

It look like that example is just strange. It’s totally fine to write as

fn mutate(r: &mut Result<i32, i32>) {
    match r.as_mut() {
        Ok(v) => *v = 42,
        Err(e) => *e = 0,
    }
}

Nevertheless, a word about &mut and ref mut in pattern bindings: since patterns match existing structure, a &mut in effect “undoes” a reference. The ref mut “creates” a reference when binding. For example:

  • &mut x matches &mut 1, and x is set to 1.
  • ref mut x matches 1, and x is set to &mut 1.
  • ref mut x matches &mut 1, and x is set to &mut &mut 1 (which is already probably unwanted).
  • &mut ref mut x matches &mut 1, and the &mut ref mut “undoes” itself; x is set to &mut 1.

The last one is what happens in the example, since as_mut produces Result<&mut A, &mut B>.


#3

Well explained, thanks!.