2

I want to change button's label when button is pressed. But I got this error message.

error[E0505]: cannot move out of `but` because it is borrowed
  --> src/main.rs:24:22
   |
24 |     but.set_callback(move || but.set_label("PRESSED"));
   |     --- ------------ ^^^^^^^ --- move occurs due to use in closure
   |     |   |            |
   |     |   |            move out of `but` occurs here
   |     |   borrow later used by call
   |     borrow of `but` occurs here

error: aborting due to previous error

The code itself

  1 use fltk::*;
  2 
  3 fn main() {
  4 
  5     let app = app::App::default().with_scheme(app::Scheme::Gleam);
  6     let mut win = window::Window::default()
  7         .with_pos(0, 0)
  8         .with_size(300, 300)
  9         .with_label("FLTK_Window");
 10     let mut but = button::Button::default()
 11         .with_pos(0, 0)
 12         .with_size(100, 50)
 13         .center_of(&win)
 14         .with_label("BUTTON");
 15     win.end();
 16     win.show();
 17     
 18     win.set_color(Color::Black);
 19     but.set_color(Color::from_rgb(0, 100, 0));
 20     but.set_label_color(Color::White);
 21     but.set_label_type(LabelType::Normal);
 22     but.set_callback(move || but.set_label("PRESSED"));
 23     app.run().unwrap();
 24 }

How I cand handle with such type of problem?

ratpoison
  • 21
  • 1

1 Answers1

1

In addition to frankenapps answer, fltk has an overloaded set_callback method (set_callback2) which gives you access to a mutable reference of the widget.

but.set_callback2(|b| b.set_label("PRESSED"));

You can also use move to capture outer variables if you need to.

Update: Since fltk-rs version 1.0, set_callback captures &mut self by default.

but.set_callback(|b| b.set_label("PRESSED"));
mo_al_
  • 561
  • 4
  • 9