Borrowed value does not live long enough in closure

Hello,

I'm trying to use closure and I don't know how use "external" variables inside closure. Example code:

        for button in buttons.iter() {
            let (id, host, port, label) = *button;

            if ctx.button(id, label).align(ui::TextAlign::Center).pressed() {
                self.display_loading = true;
                self.loading_closure = Some(Box::new(
                    || {
                        return action::Action::StartupToZone {
                            server_ip: host.to_string(),
                            server_port: port as u16,
                        };
                    })
                );
            }
        }

When call self.loading_closure.as_ref().unwrap()() :

error[E0597]: `host` does not live long enough
  --> src/gui/engine/startup.rs:82:40
   |
79 |                   self.loading_closure = Some(Box::new(
   |  _____________________________________________-
80 | |                     || {
   | |                     -- value captured here
81 | |                         return action::Action::StartupToZone {
82 | |                             server_ip: host.to_string(),
   | |                                        ^^^^ borrowed value does not live long enough
83 | |                             server_port: port as u16,
84 | |                         };
85 | |                     })
   | |______________________- cast requires that `host` is borrowed for `'static`
...
88 |           }
   |           - `host` dropped here while still borrowed

error[E0597]: `port` does not live long enough
  --> src/gui/engine/startup.rs:83:42
   |
79 |                   self.loading_closure = Some(Box::new(
   |  _____________________________________________-
80 | |                     || {
   | |                     -- value captured here
81 | |                         return action::Action::StartupToZone {
82 | |                             server_ip: host.to_string(),
83 | |                             server_port: port as u16,
   | |                                          ^^^^ borrowed value does not live long enough
84 | |                         };
85 | |                     })
   | |______________________- cast requires that `port` is borrowed for `'static`
...
88 |           }
   |           - `port` dropped here while still borrowed

error: aborting due to 2 previous errors

How to deal with that ?

You probably want a move closure that takes ownership of the things you use.

move |args| { ... }

You got it !

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.