How to mutate data using a loop ?
Hi evereryone,
Following the awesome Rust + Web Assembly tutorial, I'm trying to implement Conway's Game of Life like the tutorial explains, but in a terminal application.
The code is basically the same expect for displaying the data, which I'll do eventually using Termion.
The game of life is implemented by creating a struct called Universe
:
pub struct Universe {
width: u32,
height: u32,
cells: Vec<Cell>,
}
(Cell
is an enum, either Cell::Dead
or Cell::alive
).
The Universe is brought to its new state by calling the tick()
function :
impl Universe {
pub fn tick(&mut self) -> Self {
//content
}
}
Now in the tutorial, this function is called in a loop by the javascript code :
const renderLoop = () => {
pre.textContent = universe.render();
universe.tick();
requestAnimationFrame(renderLoop);
}
But I want to call it in my main.rs
, like so :
let mut universe = Universe::new_random();
println!("{}", universe);
println!("{}", universe.tick());
println!("{}", universe.tick());
//etc.
Ideally in a loop:
loop {
println!("{}", universe.tick());
}
Which compiles, but since tick()
's signature is pub fn tick(&mut self) -> Self
, the result of universe.tick()
is always the same, it refers to the data without mutating it.
So I changed the signature to pub fn tick(mut self) -> Self
, which fails, rustc tells me:
17 | let universe = Universe::new_random();
| -------- move occurs because `universe` has type `util::Universe`, which does not implement the `Copy` trait
20 | println!("{}", universe.tick());
| -------- value moved here
21 | println!("{}", universe.tick());
| ^^^^^^^^ value used here after move
Now I've read the book about memory allocation, I don't want to copy anything and have the memory overloaded. What I want to do is re-write the memory each time I use the tick()
function, in a loop, ideally.
What can I do?