In my code, I try to handle a situation when I have a Foo
struct which contains two vectors of Bar
structs. The Foo
is pretty much an aggregate for some logic being done on the Bar
structs. Please consider the following code:
pub struct Bar {
parent_bar: Option<Box<Bar>>,
val: i32,
}
pub struct Foo {
board: Vec<Bar>,
bars_to_further_process: Vec<Bar>,
}
impl Foo {
pub fn new(&self) -> Self {
Foo {
board: Vec::with_capacity(10),
bars_to_further_process: Vec::new(),
}
}
// ...
// some init method to populate board with Bar structs
// ...
pub fn process(&mut self) {
let mut currentBar = self.board[0];
let nextBar = self.board[1];
// do some logic and change some values of currentBar
currentBar.val = 10;
// assign next bar as parent of the current
currentBar.parent_bar = Some(Box::new(nextBar));
self.bars_to_further_process.push(currentBar);
}
}
The above, however, does not compile:
error[E0507]: cannot move out of borrowed content
--> src/astar2.rs:24:28
|
24 | let mut currentBar = self.board[0];
| ^^^^^^^^^^^^^
| |
| cannot move out of borrowed content
| help: consider borrowing here:&self.board[0]
error[E0507]: cannot move out of borrowed content
--> src/astar2.rs:25:21
|
25 | let nextBar = self.board[1];
| ^^^^^^^^^^^^^
| |
| cannot move out of borrowed content
| help: consider borrowing here:&self.board[1]
If I in fact do borrow, I get another error:
error[E0308]: mismatched types
--> src/astar2.rs:31:45
|
31 | currentBar.parent_bar = Some(Box::new(nextBar));
| ^^^^^^^ expected structastar2::Bar
, found reference
|
= note: expected typeastar2::Bar
found type&astar2::Bar
error[E0308]: mismatched types
--> src/astar2.rs:33:41
|
33 | self.bars_to_further_process.push(currentBar);
| ^^^^^^^^^^ expected structastar2::Bar
, found reference
|
= note: expected typeastar2::Bar
found type&astar2::Bar
This seems to be obvious. I have a Vec
of Bar
structs, not a Vec
of Bar
references. Should in this case bars_to_further_processing
be declared as a Vec<&Bar>
instead? If I do so, I am forced to specify lifetime parameters on the Foo
struct itself which I need to avoid, as in wasm-bindgen
it's not supported.
I am missing something here. Will be gratefull for any hints.