[英]How can I make only certain struct fields mutable?
I have a struct: 我有一个结构:
pub struct Test {
pub x: i32,
pub y: i32,
}
I'd like to have a function that mutates this — easy: 我想要一个改变这个的功能 - 简单:
pub fn mutateit(&mut self) {
self.x += 1;
}
This makes the entire struct mutable for the duration of the function call of mutateit
, correct? 这使得整个结构在
mutateit
的函数调用期间是可变的,对吗? I only want to mutate x
, and I don't want to mutate y
. 我只想变异
x
,我不希望发生变异y
。 Is there any way to just mutably borrow x
? 有没有办法可以互相借
x
?
Rust does not support field mutability at the language level, so you cannot write something like this:
Rust不支持语言级别的字段可变性,因此您不能编写如下内容:
struct Point {
mut x: i32, // This causes an error.
y: i32,
}
You need interior mutability, which is nicely described in the standard docs : 您需要内部可变性,这在标准文档中有很好的描述:
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);
}
And, if you wanted to incorporate it in a function: 并且,如果您想将其合并到一个函数中:
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.