在下面的代码中,我有一个带有只读字段
a
和一堆可读写字段的结构体 Foo
。当直接从结构体借用单独的字段时,没有任何问题。但是,当我将借用隐藏在方法调用后面时,它说我不再可以借用。#![allow(unused_variables)]
#![allow(unused_mut)]
#![allow(dead_code)]
struct Foo {
a: Vec<i32>, // Public read-only field.
pub b: Vec<f32>, // Public read-write field.
pub c: Vec<i32>, // Public read-write field.
// ... maybe more fields ...
pub z: Vec<bool>, // Public read-write field.
}
impl Foo {
pub fn new() -> Self {
Self {
a: vec![1, 2, 3],
b: vec![1.0, 2.0, 3.0],
c: vec![-3, 0, 3],
z: vec![false, true],
}
}
pub fn borrow_a(&self) -> &Vec<i32> {
&self.a
}
}
pub fn main() {
let mut foo = Foo::new();
{ // This is okay.
let x = &foo.a; // Immutably borrow `a`.
let mut y = &mut foo.b; // Mutably borrow `b`.
for i in x { } // Immutably use `a`.
}
{ // This creates an error.
let x = foo.borrow_a(); // Immutably borrow `a`.
let mut y = &mut foo.b; // Mutably borrow `b`.
for i in x { } // Immutably use `a`.
}
}
error[E0502]: cannot borrow `foo.b` as mutable because it is also borrowed as immutable
--> src/main.rs:39:21
|
38 | let x = foo.borrow_a(); // Immutably borrow `a`.
| --- immutable borrow occurs here
39 | let mut y = &mut foo.b; // Mutably borrow `b`.
| ^^^^^^^^^^ mutable borrow occurs here
40 | for i in x { } // Immutably use `a`.
| - immutable borrow later used here
有没有什么方法可以让编译器知道这段代码是正确的,而我正在借用两个不相交的字段?还是有其他符合人体工程学的解决方案?
main
中借用b
是否安全? - Jonas Berlina
不应直接被更改,即从用户的角度来看它应该是只读的字段。 - Ted Klein Bergman