Sorry if the question isn't phrased very well. The explanation and code will hopefully be better.
The following code is a strip down version of a game where a bunch of cells are drawn to the screen and once you select one it does something.
#[derive(Debug)]
struct Cell {
x: usize,
}
struct World<'a> {
cells: Vec<Cell>,
selected_cell: Option<&'a mut Cell>,
}
impl<'a> World<'a> {
fn print_cells(&self) {
for cell in &self.cells {
println!("{:?}", cell);
}
}
}
fn main() {
let mut w = World {
cells: Vec::with_capacity(20),
selected_cell: None,
};
for i in 0..w.cells.capacity() {
let c = Cell {
x: i,
};
w.cells.push(c);
}
main_loop(&mut w);
}
fn main_loop(w: &mut World) {
loop {
w.print_cells();
if true {
w.selected_cell = w.cells.get_mut(5);
}
match w.selected_cell {
Some(mut cell) => {
cell.x = 45;
println!("selected {:?}", cell);
},
None => {},
}
if true {
break;
}
}
}
The problem here is that I'm struggling with the lifetimes of the objects and The mutable/immutable references.
This gives me the error explicit lifetime required in the type of w
.
The sublime text plugin gives some tips and I tried some suggestions but none work.
fn main_loop<'a>(mut w: &'a World) { // gives me: explicit lifetime required in the type of `w`
fn main_loop<'a>(mut w: &'a World<'a>) {
The one above works but it gives several errors
At this point I'm just shooting in the dark, adding and removing &, mut, 'a and <> on everything to see if works.