我有一个结构:
pub struct Test {
pub x: i32,
pub y: i32,
}
我想要一个改变这个的函数 - 简单:
pub fn mutateit(&mut self) {
self.x += 1;
}
这使得整个结构在函数调用期间是可变的mutateit
, 正确的?我only想要变异x
,我不想变异y
。有什么办法可以可变借用x
?
Citing The Book https://doc.rust-lang.org/book/first-edition/structs.html:
Rust 不支持语言级别的字段可变性,因此您不能编写如下内容:
struct Point {
mut x: i32, // This causes an error.
y: i32,
}
您需要内部可变性,这在标准文档 https://doc.rust-lang.org/std/cell/struct.Cell.html#examples:
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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)