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

前端 未结 2 1824
被撕碎了的回忆
被撕碎了的回忆 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:33

    By using Cell you can emulate field-level mutability:

    use std::cell::Cell;
    
    struct Point {
        x: i32,
        y: Cell,
    }
    
    impl Point {
        fn up(&self) {
            self.y.set(self.y.get() + 1);
        }
    }
    
    fn main() {
        let p = Point { x: 0, y: Cell::new(0) };
        p.up();
        println!("y: {:?}", p.y);
    }
    

    This will print y: Cell { value: 7 } and we've successfully updated y.

    Additionally, if you are using nightly channel, you can declare #![feature(cell_update)] on top of your .rs file and use the following syntax inside your up() method:

    impl Point {
        fn up(&self) {
            self.y.update(|x| x + 1);
        }
    }
    

    Note: This feature above is a nightly-only experimental API.

    From The Rust Programming Language at Rust 1.7.

提交回复
热议问题