DEV Community

Cover image for Move data out of closure
Antonov Mike
Antonov Mike

Posted on • Updated on

Move data out of closure

Finally solved this issue! Entry works, I can type some text with application buttons.
This is in addition to the first and second post on the subject “Making GTK keyboard on Rust”.

We should add glib to the list of [dependencies]

glib = "0.15.12"
Enter fullscreen mode Exit fullscreen mode

And to the list of crates

use glib::clone;
Enter fullscreen mode Exit fullscreen mode

Now connect and clone!()

    button_1.connect_clicked(clone!(
        @strong entry =>
        move |_| {
            entry.insert_text("1", &mut -1);
        }
    ));
Enter fullscreen mode Exit fullscreen mode

Any time we need to move data out of closure we need to @strong clone it. After this we can use insert_text() or set() – depends on your goals.
If we want to store some value in a variable we need to @strong this variable and use Reference Counter. This is a part of standard library so we don’t need to change our Cargo.toml file.

use std::rc::Rc;
Enter fullscreen mode Exit fullscreen mode

Now create some variable of type Rc<Cell<f64>> and clone it into closure

let some_value: Rc<Cell<f64>> = Rc::new(Cell::new(0.0));
Enter fullscreen mode Exit fullscreen mode

This is the same as in the previous example

@strong entry, @strong some_value =>
Enter fullscreen mode Exit fullscreen mode

Here we go! We can type, change entry and store everything

    button_1.connect_clicked(clone!(
        @strong entry, @strong some_value =>
        move |_| {
            set_value(&some_value, 1.0);
            entry.insert_text("1", &mut -1);
        }));
// some code
pub fn set_value(some_value: &Rc<Cell<f64>>, entered_number: f64) {
    some_value.set(some_value.get() * 10.0 + entered_number);
    println!("{}", some_value.get());
}
Enter fullscreen mode Exit fullscreen mode

As you can see entry and some_value were cloned into closure. Data moved into set_value function. Here we can change our variable – it will be the result of concatenation of the previous and new value. We need get() to get data out of RC and set() to set the new one.
Now every time you press a key, you will see the updated value of the variable on the command line. For example:
1
15
158

Top comments (0)