I'm trying to write a simple calculator app to get the hang of FLTK, specifically the Rust binding. For the output I want to store a string somewhere that I can have an output set to, that way it's a little more simple to handle, but, the compiler really doesn't like that.
I'm trying to use a callback for this in a loop since I need to do it ~9-10 times for all the buttons and I would like to be able to repeat it for larger button amounts that need some standard callback.
I have tried doing the compiler's suggestion of having the closure take ownership with move
but the problem with that is I can't get the string back out to use later, since the library makes it so the function can't have a return value on top of that it doesn't make sense to hand over ownership to anonymous function that can't hand it back.
A fragment of the current code I have in my compiler is
fn main() { let mut number_buts: [Button; 10] = arr![Button::default(); 10]; let mut out_string: String = String::new(); for i in 1..number_buts.len() { let mut current_but = Button::default(); ((((j)*25))+top_pad).try_into().unwrap()); let call_back = |but: &mut Button| { out_string.push_str(but.label().clone().as_str()); }; current_but.set_callback( call_back); let _ = mem::replace(&mut number_buts[i], current_but); }}
The error I get is
error[E0373]: closure may outlive the current function, but it borrows `out_string`, which is owned by the current function --> src\main.rs:46:25 |46 | let call_back = |but: &mut Button| { | ^^^^^^^^^^^^^^^^^^ may outlive borrowed value `out_string`47 | out_string.push_str(but.label().clone().as_str()); | ---------- `out_string` is borrowed here |note: function requires argument type to outlive `'static` --> src\main.rs:50:9 |50 | current_but.set_callback( call_back); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^help: to force the closure to take ownership of `out_string` (and any other referenced variables), use the `move` keyword |46 | let call_back = move |but: &mut Button| { | ++++error[E0499]: cannot borrow `out_string` as mutable more than once at a time --> src\main.rs:46:25 |46 | let call_back = |but: &mut Button| { | ^^^^^^^^^^^^^^^^^^ `out_string` was mutably borrowed here in the previous iteration of the loop47 | out_string.push_str(but.label().clone().as_str()); | ---------- borrows occur due to use of `out_string` in closure...50 | current_but.set_callback( call_back); | ------------------------------------ argument requires that `out_string` is borrowed for `'static`