Hi all,
While having a strong C/C++ and Java background I am heavily struggling to learn some of the new concepts Rust introduces. Currently, I'm pulling out my hair trying to understand lifetimes, borrowing, and such.
I'm working on a project which uses the fltk-rs crate (Rust bindings for the FLTK GUI library). I try to setup a callback function to "draw" using the method reserved for this purpose which takes a closure. Here is a small snippet of code which I think should be sufficient to understand my problem (if required, I can also post the complete code):
fn main() {
:
let mut grid = Grid::new(); // Grid = Hashmap<T1, T2>
init_grid(&mut grid); // Initializes the grid
canvas.draw(|c| { // FLTK method setting the "draw" method
:
for (p, _) in &grid { // Iterates over the grid and draws things
:
}
});
while app.wait() { // FLTK main event loop
survivors(&grid); // Updates elements of the grid
thread::sleep(...); // Waits a bit
}
}
When building this code I get following error message(s):
rror[E0373]: closure may outlive the current function, but it borrows `grid`, which is owned by the current function
--> src/main.rs:78:17
|
78 | canvas.draw(|c| {
| ^^^ may outlive borrowed value `grid`
79 | for (p, _) in &grid {
| ---- `grid` is borrowed here
|
note: function requires argument type to outlive `'static`
--> src/main.rs:78:5
|
78 | / canvas.draw(|c| {
79 | | for (p, _) in &grid {
80 | | draw_rectf(9*p.x + c.x(), 9*p.y + c.y(), 8, 8);
81 | | }
82 | | });
| |______^
help: to force the closure to take ownership of `grid` (and any other referenced variables), use the `move` keyword
|
78 | canvas.draw(move |c| {
| ++++
However, when I use the "move" keyword as suggested I get another error (obviously because I keep using the 'grid' variable):
rror[E0382]: borrow of moved value: `grid`
--> src/main.rs:84:19
|
75 | let mut grid = Grid::new();
| -------- move occurs because `grid` has type `HashMap<Pair, u8>`, which does not implement the `Copy` trait
...
78 | canvas.draw(move |c| {
| -------- value moved into closure here
79 | for (p, _) in &grid {
| ---- variable moved due to use in closure
...
84 | survivors(&grid);
| ^^^^^ value borrowed here after move
I've tried back and forth, tried to define 'grid' as static variable, calling a static helper function from within the closure, and things like that. To no avail. I've searched this forum and found two or three similar error messages, but they are of no real help to me.
I'd very much appreciate if someone could kick me into the right direction. As I said, if you need more code just tell me.
TIA!!