How can I modify self in a closure called from a member function?

The simplest change you can make is to pass the reference to the closure:

struct Tester {
    x: i8,
}

impl Tester {
    fn traverse<F>(&mut self, mut f: F)
    where
        F: FnMut(&mut Tester),
    {
        f(self);
    }
}

fn main() {
    let mut tester = Tester { x: 8 };
    tester.traverse(|z| z.x += 1);
    println!("{}", tester.x);
}

This prevents having multiple mutable references (also known as aliasing), which are disallowed in Rust.

Leave a Comment