I try a lot of stuff and googling. Now I begin to get headache.
currently I have no idea how to get this code snippet to run.
The problem is that I can't change the way the Image and Context structures work because they came from the nanovg-rs create.
But I also want to use my Gui Struct to avoid loading a image on each frame rendering function call
use std::ptr;
// begin [fixed came from nanovg-rs crate]
struct Context(*mut u32);
impl Context {
fn new() -> Context {
Context {
0: ptr::null_mut(),
}
}
}
struct Image<'a>(&'a Context, u32);
impl<'a> Image<'a> {
fn new(ctx: &'a Context) -> Image<'a> {
Image {
0: ctx,
1: 500,
}
}
}
// end [fixed came from nanovg-rs crate]
// trying to use a GuiBuilder...
struct GuiBuilder {
context: Context,
}
impl GuiBuilder {
fn new(context: Context) -> Self {
Self {
context
}
}
pub fn build<'a>(self) -> Gui<'a> {
//load some images
let image = Image::new(&self.context);
Gui {
ctx: self.context,
img: image,
}
}
}
struct Gui<'a> {
ctx: Context, // -
img: Image<'a>, // - consumes a reference of context... is like a self referencing
}
impl <'a> Gui<'a> {
pub fn new() -> GuiBuilder {
let context = Context::new();
GuiBuilder::new(context)
}
pub fn some_test_output(&self) {
println!("hallo");
}
}
fn main() {
let testing = Gui::new().build();
testing.some_test_output()
}
Compiling playground v0.0.1 (/playground)
error[E0515]: cannot return value referencing local variable `gui`
--> src/main.rs:107:9
|
105 | gui.load_some_data();
| --- `gui` is borrowed here
106 |
107 | / App {
108 | | app_name: "Wooow".to_string(),
109 | | gui,
110 | | }
| |_________^ returns a value referencing data owned by the current function
error[E0505]: cannot move out of `gui` because it is borrowed
--> src/main.rs:109:13
|
102 | impl<'a> App<'a> {
| -- lifetime `'a` defined here
...
105 | gui.load_some_data();
| --- borrow of `gui` occurs here
106 |
107 | / App {
108 | | app_name: "Wooow".to_string(),
109 | | gui,
| | ^^^ move out of `gui` occurs here
110 | | }
| |_________- returning this value requires that `gui` is borrowed for `'a`
error: aborting due to 2 previous errors
Some errors have detailed explanations: E0505, E0515.
For more information about an error, try `rustc --explain E0505`.
error: Could not compile `playground`.
To learn more, run the command again with --verbose.
The issue is if Gui is moved then its self-reference will dangle. There are multiple ways to attack this problem, but one way is not owning the referenced value but requires the caller to own the value.
So the types will be: