我有一个简单的程序,其中有一个字符串向量。按一个按钮即可将项目添加到该向量中。按另一个按钮应该打印出该向量的当前内容。我的代码如下:
use fltk::{app, button::Button, prelude::*, window::Window};
fn main() {
let app = app::App::default();
let mut wind = Window::new(100, 100, 400, 300, "File Manager");
let mut filenamelist: Vec::<String> = vec![];
// Create buttons
let mut add_item_btn = Button::new(50, 50, 100, 40, "Select File");
let mut show_list_btn = Button::new(50, 120, 100, 40, "Show List");
let mut exit_btn = Button::new(50, 190, 100, 40, "Exit");
// Button callbacks
{
let mut filenamelist = filenamelist.clone();
add_item_btn.set_callback(move |_| {
filenamelist.push("ITEM_TO_BE_ADDED".to_string());
println!("\nList in add_item_btn callback fn:");
for f in filenamelist.iter() { // THIS SHOWS ITEM IS ADDED TO THE VECTOR;
println!("{}", f);
}
} );
}
{
let filenamelist = filenamelist.clone();
show_list_btn.set_callback(move |_| {
println!("\nList in show_list_btn callback fn:");
for f in filenamelist.iter() { // THIS ALWAYS SHOWS EMPTY VECTOR;
println!("{}", f);
}
});
}
exit_btn.set_callback(|_| {
app::quit();
});
wind.end();
wind.show();
app.run().unwrap();
}
我使用命令
cargo run
在 Linux 中构建并运行应用程序。它构建没有错误。有一个警告:
let mut filenamelist
help: remove this `mut`
note: `#[warn(unused_mut)]` on by default
但是,随着应用程序运行,如上面代码中的注释中所述,该项目被添加到 add_item_btn.set_callback 函数中的列表中,但 show_list_btn.set_callback 函数始终显示一个空列表。
错误在哪里,如何解决?
在互联网上不同资源的帮助下,我已经能够解决问题并使用以下代码运行程序:
use fltk::{app, button::Button, prelude::*, window::Window};
use std::cell::RefCell;
use std::rc::Rc;
fn showlist(flist: &Rc<RefCell<Vec<String>>>){
for f in flist.borrow().iter(){
println!("item: {}", f);
}
}
fn main() {
let app = app::App::default();
let mut wind = Window::new(100, 100, 200, 300, "File Manager");
let filenamelist: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::<String>::new()));
// Create buttons
let mut select_file_btn = Button::new(50, 50, 100, 40, "Select File");
let mut show_list_btn = Button::new(50, 120, 100, 40, "Show List");
let mut exit_btn = Button::new(50, 190, 100, 40, "Exit");
let filenamelist_cl1 = filenamelist.clone();
select_file_btn.set_callback(move |_| {
println!("\nList in select_file_btn callback fn:");
filenamelist_cl1.borrow_mut().push("ITEM ADDED".to_string());
showlist(&filenamelist_cl1);
} );
let filenamelist_cl2 = filenamelist.clone();
show_list_btn.set_callback(move |_| {
println!("\nList in show_list_btn callback fn:");
showlist(&filenamelist_cl2);
});
//let filenamelist_cl3 = filenamelist.clone();
exit_btn.set_callback(move|_| {
println!("\nList before quitting:");
showlist(&filenamelist);
app::quit();
});
wind.end();
wind.show();
app.run().unwrap();
}