I'm still relatively new to Rust and often enough it feels like I need to "shove-in' entire code blocks (from discrete methods) into the same code block because either:
- a) I don't master Rust's ownership <--- which is mighty likely
- b) there's no other way.
A random example I found online: https://github.com/Rust-SDL2/rust-sdl2/blob/master/examples/game-of-life.rs pretty much demonstrate what I mean.
In this example, (although the duplication is trivial) I feel that a method to draw a square of a given color might have been used rather than duplicating such code 3 times.
This is pretty much exactly the challenge I often face. Rather than creating a method such as draw_square(&self, &mut WindowCanvas, color: Color) I have to shove-in the entire body of such method because the Rust's ownership feature won't allow me breaking my code into discrete methods and pass that texture_canvas around because of usage of &self or that &mut canvas from closure.
For example, I can't manage to find the proper syntax to write such construct:
// Set the render target to the texture
self.canvas.with_texture_canvas(&mut self.texture, |texture_canvas| {
// Clear the virtual canvas
texture_canvas.set_draw_color(Color::RGB(255, 255, 255));
texture_canvas.clear();
// Rendering content on the virtual canvas
self.draw_cells(texture_canvas);
self.draw_path(texture_canvas);
self.draw_extra_widgets(texture_canvas);
}).unwrap();
EDIT For completeness, here is another example (probably a typical proper one) where drawing to canvas is kept to minimum and game objects are fully decoupled from SDL/Drawing: https://sunjay.dev/learn-game-dev/ecs-refactor-multiple-modules.html