Hey all,
I am trying to make a macro where an indefinite number of closures can be passed, then in the macro the closures are collected in a vector.
I could come up with a solution, but I am not pleased with it. Here is what I have:
First I have a test object, for the sake of the test:
struct TestObject {
name: String,
age: i32
}
And here is the macro for collecting the passed closures and Boxing them:
#[macro_export]
macro_rules! actions {
($TStructType:ident, $($closure:expr),*) => {
{
let mut temp_vec = Vec::<Box<dyn Fn(&$TStructType)>>::new();
$(
temp_vec.push(Box::new($closure));
)*
temp_vec
}
};
}
And here is a unit test for the functionality:
#[cfg(test)]
mod test {
use super::*;
#[test]
pub fn test_actions_macro(){
let closure1 = |item1: &TestObject| println!("{}",item1.name);
let closure2 = |item2: &TestObject| println!("{}",item2.age);
let actions: Vec<Box<dyn Fn(&TestObject)>> = actions!(TestObject, closure1, closure2);
//Additional logic with using the actions vector
}
}
To be honest I am not pleased with this solution because we always need to pass the type of the closure input parameter, in this case TestObject
.
Is there any way to use a wildcard or so in my macro actions
for TStructType
? From the user experience point of view, I would be really happy to get rid of this param of this macro, so only specifying the closures.
Here is a playground link for the code.
Thanks in advance for the help!