macro_rules! clone_async {
(
$( $ident:ident $(= $expr:expr)? , )*
|| $($tt:tt)*
) => { ... };
(
$( $ident:ident $(= $expr:expr)? , )*
| $($args:pat_param),* $(,)? | $($tt:tt)*
) => { ... };
}Expand description
Clones variables into an async closure (by calling ToOwned::to_owned).
The closure will automatically be turned into a
move || async move {...} closure. Closure arguments are supported.
All variables will be cloned immediately for the closure to own the variable. The variable will also be cloned every time the closure is called, so that the async body can also own the variables.
§Examples
Expansion:
let thing = String::from("important info");
let foo = String::from("bar");
clone_async!(thing, foo, || {
println!("some {thing} from {foo}");
});
// Expands to:
// let thing = thing.to_owned();
// let foo = foo.to_owned();
// move || {
// let thing = thing.to_owned();
// let foo = foo.to_owned();
// async move {
// println!("some {thing} from {foo}");
// }
// }This will most often be used in the context of adding callbacks to list items.
ⓘ
let thing = String::from("important info");
let foo = String::from("bar");
ListItem::new("title")
.on_activate(clone_async!(thing, || {
println!("some {thing}");
todo!()
}))
.on_hotkey_activate(clone_async!(foo, |hotkey| {
println!("foo {foo}! got hotkey {hotkey:?}");
todo!()
}));If you have a more complex expression that you want to clone, you can
bind it to an identifier using ident = expr syntax.
ⓘ
let thing = String::from("important info");
let item = ListItem::new("get me out of here");
ListItem::new("i got u")
.on_activate(clone_async!(thing, title = item.title, || {
println!("got {title} out of there with {thing}");
todo!()
}));