Almost: you've forgotten to double-check whether the optional parameters have been passed or not:
macro_rules! declare_function {
($func: ident $(, $param: ident, $param_type: ty)? ) => {
// first, specify the parameters only if they were passed
fn $func( $( $param: $param_type )? ) {
$( // second, create the vector only if there's data for it
let v: Vec< $param_type > = vec![ $param ];
println!("{:?}", v);
)?
// the following isn't going to work, though:
// let v $(: Vec<$param_type> )? = vec![ $($param)? ];
// println!("{:?}", v);
// error[E0282]: type annotations needed for `Vec<T>`
// (Rust won't let you create a function for a vector,
// holding objects of a type, not known beforehand)
}
};
}
fn main(){
declare_function!(foo);
foo(); // won't print anything
let a: i32 = 321;
declare_function!(bar, a, i32);
bar(a); // will print a Vec with the contents of a
}