Rust (+SFML) - How to avoid extra object construction when limited by lifetime parameters? -


i'm using rust-sfml (rsfml::graphics) to, @ moment, draw pixels screen. (i'm starting both rust , project.) i'm storing data in image, copying texture.

this texture used create sprite<'s>; herein lies problem. need able mutate texture, type of sprite<'s> seems guarantee can't want. since need able call window.draw(&sprite) every time window redrawn, i'm creating new sprite each time.

the preferable alternative keep sprite<'s> in struct render along texture. since 'sprite' has lifetime parameter, becomes struct render<'s>:

struct render<'s> {     texture: texture,     sprite: sprite<'s>, } 

i have method on render:

fn blit(&'s mut self) -> () 

which mutates render (by editing texture). now, try call blit more once, run problem:

render.blit(); render.blit();  // error: cannot borrow `render` mutable more once @ time 

which, think, happens because lifetime parameter forces the render's lifetime-as-borrowed-by-the-first-blit-call equal lifetime of render instance (the whole main function).

how can keep original sprite , continue able mutate container? possible?

here stupid-looking , minimal example:

extern crate rsfml;  use rsfml::graphics::sprite;  fn main() -> () {     let mut render = render::new();     render.blit();     render.blit();  // error: cannot borrow `render` mutable more once @ time }  struct render<'s> {     sprite: option<sprite<'s>>, }  impl<'s> render<'s> {     fn new() -> render { render { sprite: none } }     fn blit(&'s mut self) -> () { } } 

(apologies if question not clear. it's difficult express when i'm not familiar concepts.)

when call blit, there 2 lifetimes under consideration; self, see, of type &'ρ₀ render<'ρ₁> lifetimes ρ₀ , ρ₁. in impl<'s> render<'s> declaration, have declared ρ₁ 's, , in &'s mut self have declared ρ₀ 's: thus, lifetime of borrow of self is 's, means can ever have 1 borrow survive until destruction of type—it has been declared “at least long type being referred to”.

you want alter introduce new lifetime parameter blit function permitted less 's; wish ρ₀ minimal, tied return value (as presume using 's—if not, should omit , allow compiler infer we’re write explicitly). way, borrow active while return value of function still in scope (in trivial example, it’s not used , can take reference).

this, then, alteration function needs done:

fn blit<'a>(&'a mut self) { } 

if alter have return value , use it, you’ll need make sure out of scope before call blit again. may mean passing directly function, or may mean introducing new scope, this:

{     let foo = render.blit();     // … things foo … gets freed @ end of block. } render.blit(); 

Comments

Popular posts from this blog

google api - Incomplete response from Gmail API threads.list -

Installing Android SQLite Asset Helper -

Qt Creator - Searching files with Locator including folder -