我如何在其自己的回调中访问FLTK按钮? [重复]

问题描述 投票:0回答:1
我正在尝试学习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方法时,我已经将其用作可变对象。我不知道该如何解决此问题。
rust borrow-checker fltk
1个回答
0
投票
@ 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())) }));

程序现在可以按预期编译并运行。
© www.soinside.com 2019 - 2024. All rights reserved.