How to capture external variable in a closure with move [Noob question]

Hey Guys, How is it going?

I am new to RustLang, and I have a noob question for you:

How can I pass a string variable to a closure which I should use move to get the ownership of each variable inside it.

I want to pass the variable message to the closure in the second parameter of teloxide::repl .

let bot = Bot::from_env().auto_send();
let message = format!("Store: {} Link: {}", result.name, result.link);
teloxide::repl(bot, |messenger| async move {
    messenger.answer(message);
    respond(())
}).await

but I got the error:

   |
81 |                       let message = format!("Store: {} Link: {}", result.name, result.link);
   |                           ------- captured outer variable
82 |                       teloxide::repl(bot, |messenger| async move {
   |  ________________________________________________________________^
83 | |                         messenger.answer(message);
   | |                                          -------
   | |                                          |
   | |                                          move occurs because `message` has type `String`, which does not implement the `Copy` trait
   | |                                          move occurs due to use in generator
84 | |                         respond(())
85 | |                 }).await
   | |_________________^ move out of `message` occurs here

Thank you all!

You should be able to put

messenger.answer(message.clone());

to duplicate the string, instead of consuming it.

In the midst of despair I've tried to do this already ahahahaha, unfortunately it doesn't work... I can't perform any operation with this variable inside the closure =( .

Any other solutions?

Perhaps this is a case where you need to clone it in the closure instead of the future.

teloxide::repl(bot, move |messenger| {
    let message = message.clone();
    async move {
        messenger.answer(message);
        respond(())
    }
}).await
2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.