I am trying to write a game component in sdl2. I want to pass the canvas to it but the borrow checker wont let me do that. I want my component to get an immutable borrow in its contructor and then use canvas to create textures and draw but when i try to use canvas in my calling method it wants a mutable borrow. Im guessing this ia common thing and im just not getting my head around it:
extern crate sdl2;
use sdl2::render::Canvas;
use sdl2::video::{Window};
pub struct Snow<'a> {
particles: u32,
canvas: &'a Canvas<Window>
}
impl<'a> Snow<'a> {
pub fn new(parts: u32, canvas: &'a Canvas<Window>) -> Self {
Snow {
particles: parts,
canvas: canvas
}
}
}
And then use it like:
let mut canvas = window.into_canvas()
.target_texture()
.present_vsync()
.build()
.unwrap();
let snow1 = Snow::new(12, &canvas);
canvas.set_draw_color(Color::RGB(0,0,0)); <- blows up here .. cannot borrow mutable
canvas.clear();
canvas.present();
Is the snow object holding a reference to the canvas a showstopper? should i instead pass the canvas with each render call on a component or something? any pointers would be appreciated. That or a link to some established codebase that is showing component based game building using rust and sdl2...