我有一个Storage
结构,其中一个Box
指向堆上的某些数据。该存储结构具有一种方法,该方法可以对其自身进行突变并返回对其堆上数据的不可变引用。我试图以循环方式获取这些引用,并将它们存储在哈希映射(或任何其他集合)中,但无法编译。
use std::collections::HashMap;
#[derive(Copy, Clone)]
struct Data {
x: i32,
y: i32,
}
struct Storage {
ds: Box<[Data; 10]>,
}
impl Storage {
fn new() -> Storage {
Storage {
ds: Box::new([Data { x: 8, y: 6 }; 10]),
}
}
// &mut self is necessary because I need to mutate some fields in
// the actual code
fn get(&mut self, i: usize) -> &Data {
&self.ds[i]
}
}
fn main() {
let mut s = Storage::new();
let mut m: HashMap<i32, &Data> = HashMap::new();
// get the reference and insert it into hashmap
for i in 0..10usize {
let p = s.get(i);
m.insert(i as i32, p);
}
}
编译器抱怨:
error[E0499]: cannot borrow `s` as mutable more than once at a time
--> src/main.rs:33:17
|
33 | let p = s.get(i);
| ^ mutable borrow starts here in previous iteration of loop
但是p
是不可变的引用,方法调用中的可变引用应在方法返回时结束。