我有一个结构:
pub struct Test {
pub x: i32,
pub y: i32,
}
我想拥有一个可以突变的函数 - 简单:
pub fn mutateit(&mut self) {
self.x += 1;
}
这使整个结构在mutateit
函数调用的持续时间内可变,对吗?i 唯一要突变x
,我不想突变y
。有什么方法可以借用x
?
引用书:
Rust不支持语言级别的字段可变性,因此您不能写下类似的内容:
struct Point {
mut x: i32, // This causes an error.
y: i32,
}
您需要内部可突变性,这在标准文档中得到了很好的描述:
use std::cell::Cell;
pub struct Test {
pub x: Cell<i32>,
pub y: i32
}
fn main() {
// note lack of mut:
let test = Test {
x: Cell::new(1), // interior mutability using Cell
y: 0
};
test.x.set(2);
assert_eq!(test.x.get(), 2);
}
,如果您想将其合并到功能中:
impl Test {
pub fn mutateit(&self) { // note: no mut again
self.x.set(self.x.get() + 1);
}
}
fn main() {
let test = Test {
x: Cell::new(1),
y: 0
};
test.mutateit();
assert_eq!(test.x.get(), 2);
}