[英]How I can mutate a struct's field from a method?
我想做這個:
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 中,可變性是繼承的:數據的所有者決定值是否可變。 然而,引用並不意味着所有權,因此它們本身可以是不可變的或可變的。 您應該閱讀解釋所有這些基本概念的官方書籍。
通過使用Cell<T>
您可以模擬字段級可變性:
use std::cell::Cell;
struct Point {
x: i32,
y: Cell<i32>,
}
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);
}
這將打印y: Cell { value: 7 }
並且我們已經成功更新了y
。
此外,如果您使用nightly
頻道,您可以在.rs
文件頂部聲明#![feature(cell_update)]
並在up()
方法中使用以下語法:
impl Point {
fn up(&self) {
self.y.update(|x| x + 1);
}
}
注意:上面的這個功能是一個只在夜間使用的實驗性 API。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.