Changing values through `Option<&mut T>` in a struct

It’s still barely possible to avoid the mut marker on o.

    {
        let mut i = 3;
        let mut j = 5;
        let o = B {
            i: [Some(&mut i), Some(&mut j)],
        };

        if let Some(&mut ref mut v) = o.i[0] {
            *v += 3;
        }
    }

Yes… the &mut ref mut v pattern looks a bit ridiculous, but it works :sweat_smile:

The fact that this works also relies on the fact that array-indexing is compiler-implemented and doesn’t use the IndexMut trait, otherwise, the indexing operation would require mutable access to the array itself.

6 Likes