【问题标题】:How do I access a FLTK button inside its own callback? [duplicate]如何在自己的回调中访问 FLTK 按钮? [复制]
【发布时间】:2020-04-07 14:24:08
【问题描述】:

我正在尝试学习 Rust,并决定尝试使用 FLTK crate。但是,我在尝试访问其自己的回调中的按钮时遇到了一些问题,我不知道如何解决它。

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 方法时我已经将它用作可变对象。我不知道我应该如何解决这个问题。

【问题讨论】:

标签: rust borrow-checker fltk


【解决方案1】:

@Shepmaster 链接了Problems with mutability in a closure,它为此提供了解决方案。

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()))
    }));

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 2015-09-16
    • 1970-01-01
    • 2019-07-12
    • 1970-01-01
    相关资源
    最近更新 更多