4 ms·
You cannot access "bot" inside bot.on_speak(|| { ... }) because Rust does not know that the "bot" variable stays alive for whenever the callback is called. In t
by rav 5y ago
You cannot access "bot" inside bot.on_speak(|| { ... }) because Rust does not know that the "bot" variable stays alive for whenever the callback is called. In this situation I would expect "bot" to be stored in an Arc, and then you would move a clone of the Arc into the callback:
let bot = Arc::new(bot);
bot.on_speak({ let bot = bot.clone(); move |evt: SpeakEvt| { ... }});
Edit to add: Alternatively, the bot could pass a mutable reference to itself to the callback when it is invoked.
bot.on_speak(|bot, evt: SpeakEvt| { ... })
- alain_gilbert 5y agoeasier said than done though. I tried the second option (calling callback with a mut reference to self) but I couldn't make it all work. I think I also had issues with "async" in a closure that could not be done. Anyway, if you can make it work, I'll study your code religiously !
- masklinn 5y ago> I think I also had issues with "async" in a closure that could not be done. Yes, async closures are not currently stable, which is a huge pain in the ass: you have to use a regular closure with an `async` block inside, but said async block will usually need to be an `async move` block, which requires more contorsions because you can't just use stuff the closure owns as that'd make said closure FnOnce (the closure's item is moved into the `async move` block meaning the closure is destroyed). This is usually solved by putting the item behind an `Arc` (if it's too costly to be directly copied, or if you want / need to mutate it), this way you can `clone()` the arc so the async move block has its own "copy". Alternatively, have the closure immediately and only call into an async function or method. I can't wait for async closures, though, I'm sure others have their own bugbears but that's by far my biggest pain in the ass when using async rust.
- rav 5y agoHere you go: https://github.com/alaingilbert/rust-ttapi/pull/1 https://github.com/alaingilbert/rust-ttapi/pull/1