我有一个 Context
结构体:
struct Context {
name: String,
foo: i32,
}
impl Context {
fn get_name(&self) -> &str {
&self.name
}
fn set_foo(&mut self, num: i32) {
self.foo = num
}
}
fn main() {
let mut context = Context {
name: "MisterMV".to_owned(),
foo: 42,
};
let name = context.get_name();
if name == "foo" {
context.set_foo(4);
}
}
在一个函数中,我需要首先获取
context
的name
,并根据我拥有的name
更新foo
。let name = context.get_name();
if (name == "foo") {
context.set_foo(4);
}
代码无法编译,因为
get_name()
接受 &self
而 set_foo()
接受 &mut self
。换言之,在同一作用域内,我对 get_name()
拥有不可变的借用,但同时也对 set_foo()
拥有可变的借用,这与引用规则相违背。
错误信息类似于:在任何时候,你可以拥有一个(但不能同时拥有)可变引用或任意数量的不可变引用。
error[E0502]: cannot borrow `context` as mutable because it is also borrowed as immutable
--> src/main.rs:22:9
|
20 | let name = context.get_name();
| ------- immutable borrow occurs here
21 | if name == "foo" {
22 | context.set_foo(4);
| ^^^^^^^ mutable borrow occurs here
23 | }
24 | }
| - immutable borrow ends here
我想知道如何解决这种情况?
&String
->&str
,这是String
的借用类型。我不打算更改您的方法名称,但请知道通常Rust获取器的风格仅为变量名称,而不是get_variable
,因此是Context::name(&self)
而不是Context::get_name(&self)
。无大碍,只是想让您知道。 - Linearset_x
是标准用法,但我不确定。个人经验来看,更常见的是使用x_mut
,它返回一个可变引用到该变量。(但显然有时你可能需要一个 setter 而不是暴露原始变量)。 - Linear