如何从方法中改变结构的字段? [英] How I can mutate a struct's field from a method?

查看:82
本文介绍了如何从方法中改变结构的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这样做:

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

但是此代码引发了编译器错误:

But this code throws a compiler error:

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变量可变:

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

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

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.

这篇关于如何从方法中改变结构的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆