rust - 我如何从方法中改变结构的字段?

标签 rust mutable

我想这样做:

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

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

fn main() {
    let p = Point { x: 0, y: 0 };
    p.up();
}

但是这段代码会抛出一个编译器错误:

error[E0594]: cannot assign to field `self.y` of immutable binding
 --> src/main.rs:8:9
  |
7 |     fn up(&self) {
  |           ----- use `&mut self` here to make mutable
8 |         self.y += 1;
  |         ^^^^^^^^^^^ cannot mutably borrow field of immutable binding

最佳答案

您需要使用 &mut self 而不是 &self 并使 p 变量可变:

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();
}

在 Rust 中,可变性是继承的:数据的所有者决定该值是否可变。然而,引用并不意味着所有权,因此它们本身可以是不可变的或可变的。您应该阅读 official book其中解释了所有这些基本概念。

关于rust - 我如何从方法中改变结构的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27022848/

相关文章:

rust - 如何在 Option<T> 中访问 T 而不会导致移动?

arrays - Haskell 中如何实现可变数组?

rust - 检索对树值的可变引用

rust - 在二维数组中赋值

printf - 为 Vec<T> 实现 fmt::Display

reference - 循环中的可变借用

python - 使用外部函数更新内部 python 类参数

reference - 使用可变引用遍历递归结构并返回最后一个有效引用

rust - Vanilla Rust中的目录遍历

rust - 在添加每个值后将 Vec<String> 连接到 String 中