Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Struct method to modify fields

  • impl

  • mut

  • &mut

  • We can add methods to a struct using the impl keyword (we implement the method) that will modify the struct.

  • For this we need to write &mut self in the method and the struct instance must be also mutable.

struct Point {
    x: i32,
    y: i32,
}

impl Point {
    fn mv(&mut self, dx: i32, dy: i32) {
        self.x += dx;
        self.y += dy;
    }
}

fn main() {
    let mut pnt = Point { x: 2, y: 3 };
    println!("x: {}", pnt.x);
    println!("y: {}", pnt.y);

    pnt.mv(4, 5);
    println!("x: {}", pnt.x);
    println!("y: {}", pnt.y);
}
x: 2
y: 3
x: 6
y: 8