我想这样做:
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/