rust - Problems with lifetimes when one instance of a struct needs a reference to another -


i'm trying write simple game sfml , rust, borrow-checker proving greatest enemy on journey.

there bunch of cases sfml needs reference object. in code below, need reference font or else text doesn't show user.

problem is, i've tried bunch of things , reference never lives long enough. works if create text object on draw method, avoid creating things inside main loop of application.

is case should take onto unsafe operations? there combination of rc, refcell, box, etc. meets needs?

please try explain me should doing , wrong in current mindset, if possible.

extern crate sfml;  use sfml::system::{ clock, vector2f }; use sfml::graphics::{ color, font, rendertarget, renderwindow, text, transformable };  pub struct fpsmeter<'a> {     position: vector2f,     clock:    clock,     value:    f32,      text:     text<'a> }  impl<'a> fpsmeter<'a> {     pub fn new() -> self {         let font = match font::new_from_file("assets/sansation.ttf") {             some(fnt) => fnt,             none      => panic!("cannot open resource: sansation.ttf"),         };          let mut text = text::new_init(             &format!("fps: {}", 0),             &font,             20           ).expect("could not create text");          fpsmeter {             position: vector2f::new(0., 0.),             clock:    clock::new(),             value:    0.,              text: text,         }     }      pub fn set_position2f(&mut self, x: f32, y: f32) {         self.position.x = x;         self.position.y = y;     }      pub fn restart(&mut self) {         self.value = 1. / self.clock.restart().as_seconds();     }      pub fn draw(&mut self, window: &mut renderwindow) {         self.text.set_position(&self.position);         self.text.set_color(&color::white());          window.draw(&self.text);     } } 

i'm not familiar rust-sfml, might misreading issue, should this. have font , text (that don't control, they're constructed library) text holds reference font. simplified:

struct font; struct text<'a> { font: &'a font } 

then have fpsmeter (that control) has text field. again, simplified:

struct fpsmeter<'a> {     text: text<'a> } 

now, if that's case, don't think can create text (or @ least font) in same method create fpsmeter, reference font can't escape stack frame of constructor function. need pass pre-built text constructor. instance:

impl<'a> fpsmeter<'a> {     fn new(txt: text<'a>) -> fpsmeter<'a> {         fpsmeter { text: txt }     }  } 

or possibly:

impl<'a> fpsmeter<'a> {     fn new(fnt: &'a font) -> fpsmeter<'a> {         fpsmeter { text: text { font: fnt } }     }  } 

toy example on playground


Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

c - Unrecognised emulation mode: elf_i386 on MinGW32 -