EDIT: Updated my code snippet to better capture the issue
So I'm running into an issue getting the following scenario to work.
fn main() {
print!("testing");
let mut game = MyGame {
player: Player { },
camera: Camera::new()
};
game.camera.set_focus_target(Some(&game.player));
}
struct MyGame<'a> {
player: Player,
camera: Camera<'a>,
}
impl<'a> MyGame<'a> {
pub fn foo(&mut self) {
self.camera.set_focus_target(Some(&self.player));
}
}
pub struct Player {
}
impl CameraFocusable for Player {
fn get_focus_position(&self) -> [f32; 2] {
[0.0, 0.0]
}
}
impl<'a> Camera<'a> {
pub fn new() -> Camera<'a> {
Self {
focus: [0.0, 0.0],
focus_target: None
}
}
pub fn set_focus(&mut self, focus: [f32; 2]) {
self.focus = focus;
}
pub fn set_focus_target(&mut self, focus_target: Option<&'a dyn CameraFocusable>) {
self.focus_target = focus_target;
}
}
pub struct Camera<'a> {
focus: [f32; 2],
focus_target: Option<&'a dyn CameraFocusable>,
}
pub trait CameraFocusable {
fn get_focus_position(&self) -> [f32; 2];
}
This line
self.camera.set_focus_target(Some(&self.player));
causes this error:
cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
expected `&mut Camera<'_>`
found `&mut Camera<'a>`rustcE0495
main.rs(89, 15): first, the lifetime cannot outlive the anonymous lifetime defined here...
main.rs(90, 43): ...so that reference does not outlive borrowed content
main.rs(88, 6): but, the lifetime must be valid for the lifetime `'a` as defined here...
main.rs(90, 21): ...so that the types are compatible
Any idea how to get this approach to work? My desire is that Camera can have a reference to a struct that implements CameraFocusable that it can use to focus on.
Is this an anti-pattern in rust? Ultimately, this should be accomplished relatively simply, right?