Skip to content

re: Frontend development with Rust part 2 VIEW POST


Great series! I'm very new to Rust but I find the possibilities for front end development one of the coolest things about it.

Would you mind showing what it would look like to create a clone of the button beforehand and manipulate it inside the closure? Thanks


Sure thing!

Notice the move keyword before the closure, this tells the compiler to move the values accessed inside the closure. I'm using this to tick the counter.

Here's one way of doing this that seems like it should work:

button.add_event_listener(move |_: ClickEvent| {
    // Code that accesses button

Although this looks perfectly fine, this won't compile. This is because when calling the method on button it must live until the end of the method:

});<--- here

But, it is moved inside the closure, making its lifetime end here:


This causes a paradox and won't compile. To fix this in my example im calling the method on a clone of the button. This way, the clone's lifetime will extend past the end of the closure but the actual button will die at the end of it. This means I will not be able to access the button variable because it is essentially out of scope.

To fix this and be able to use it later, simply do the following:

button = btn.clone();
btn.add_event_listener( ... 

And use button in the closure. This will leave btn still in scope for me to use later.


That's awesome, thanks. That way the actual button will live on and we can simply just clone it whenever we want to use it again. Sweet!

Except for event listeners or other times the value is moved you don't even have to clone it.

code of conduct - report abuse