How to refractor my self-referential struct

playground

struct App<'a> {
    data: Vec<i64>,
    ui: UI<'a>
}

struct UI<'a> {
    ui_data: Option<&'a Vec<i64>>,
    // other fields
}

impl UI<'_> {
    pub fn draw(self) {
       // do something with ui_data
        self.ui_data;
    }
}

impl<'a> App<'a> {
    pub fn new() -> Self {
        let data = vec![1,2,3,4];
        App {
            data,
            ui: UI {
                ui_data: None
            }
        }
    }
    
    pub fn post_init(&'a mut self) {
        self.ui.ui_data = Some(&self.data);
    }
}


fn func(app: App) {
    app.ui.draw()
}

pub fn main() {
    let mut app = App::new();
    app.post_init();
    
    func(app);
}

The compiler complains

error[E0505]: cannot move out of `app` because it is borrowed
  --> src/main.rs:29:10
   |
26 |     let mut app = App::new();
   |         ------- binding `app` declared here
27 |     app.post_init();
   |     --- borrow of `app` occurs here
28 |     
29 |     func(app);
   |          ^^^
   |          |
   |          move out of `app` occurs here
   |          borrow later used here

Maybe making func(app) to func(&app) is a solution. But what if I don't want to use this solution?

Delete the ui field and use &self.data.

(If there's some reason you feel you can't, you haven't demonstrated it in your OP.)

1 Like

Thanks for your reply. I update my code!

Split up your struct(s) into owned and borrowed types.

1 Like

Looks good to me. Thanks a lot

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.