如何在FLTK按钮自己的回调中访问它



我正在努力学习Rust,并决定玩FLTK机箱。然而,我在尝试访问按钮内部的回调时遇到了一些问题,我不确定如何绕过它

use fltk::{app::*, button::*, frame::*, window::*};
fn main() {
let app = App::default();
let mut window = Window::new(100, 100, 400, 300, "Hello world!");
let mut frame = Frame::new(0, 0, 400, 200, "");
let mut button = LightButton::default()
.with_pos(10, 10)
.with_size(80, 40)
.with_label("Clickity");
button.set_callback(Box::new(|| {
println!("Button is {}", button.is_on());
frame.set_label(&format!("{}", button.is_on()))
}));
window.show();
app.set_scheme(AppScheme::Gleam);
app.run().unwrap();
}

导致以下错误:

error[E0502]: cannot borrow `button` as mutable because it is also borrowed as immutable
--> src/main.rs:15:5
|
15 |       button.set_callback(Box::new(|| {
|       ^      ------------          -- immutable borrow occurs here
|       |      |
|  _____|      immutable borrow later used by call
| |
16 | |         println!("Button is {}", button.is_on());
| |                                  ------ first borrow occurs due to use of `button` in closure
17 | |         frame.set_label(&format!("{}", button.is_on()))
18 | |     }));
| |_______^ mutable borrow occurs here

据我所知,我无法在回调中访问button,因为在对其调用set_callback方法时,我已经将其用作可变对象了。我不知道该如何解决这个问题。

@Shepmaster在闭包中链接了具有可变性的问题,这为它提供了解决方案。

button改为

let button = ::std::cell::RefCell::new(
LightButton::default()
.with_pos(10, 10)
.with_size(80, 40)
.with_label("Clickity"),
);

回调改为:

button.borrow_mut().set_callback(Box::new(|| {
let button = button.borrow();
println!("Button is {}", button.is_on());
frame.set_label(&format!("{}", button.is_on()))
}));

该程序现在按预期进行编译和运行。

最新更新