How I can mutate a struct's field from a method?

前端 未结 2 1828
被撕碎了的回忆
被撕碎了的回忆 2020-12-13 12:15

I want to do this:

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

impl Point {
    fn up(&self) {
        self.y += 1;
    }
}

fn main() {
    let p = Point          


        
2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-13 12:31

    You need to use &mut self instead of &self and make the p variable mutable:

    struct Point {
        x: i32,
        y: i32,
    }
    
    impl Point {
        fn up(&mut self) {
            // ^^^ Here
            self.y += 1;
        }
    }
    
    fn main() {
        let mut p = Point { x: 0, y: 0 };
        //  ^^^ And here
        p.up();
    }
    

    In Rust, mutability is inherited: the owner of the data decides if the value is mutable or not. References, however, do not imply ownership and hence they can be immutable or mutable themselves. You should read the official book which explains all of these basic concepts.

提交回复
热议问题