Introduction
In this lab, we explore variadic interfaces, which are interfaces that can take an arbitrary number of arguments. As an example, we modify the calculate! macro from the previous section to be variadic, allowing it to evaluate multiple expressions at once.
Note: If the lab does not specify a file name, you can use any file name you want. For example, you can use
main.rs, compile and run it withrustc main.rs && ./main.
Variadic Interfaces
A variadic interface takes an arbitrary number of arguments. For example, println! can take an arbitrary number of arguments, as determined by the format string.
We can extend our calculate! macro from the previous section to be variadic:
macro_rules! calculate {
// The pattern for a single `eval`
(eval $e:expr) => {
{
let val: usize = $e; // Force types to be integers
println!("{} = {}", stringify!{$e}, val);
}
};
// Decompose multiple `eval`s recursively
(eval $e:expr, $(eval $es:expr),+) => {{
calculate! { eval $e }
calculate! { $(eval $es),+ }
}};
}
fn main() {
calculate! { // Look ma! Variadic `calculate!`!
eval 1 + 2,
eval 3 + 4,
eval (2 * 3) + 1
}
}
Output:
1 + 2 = 3
3 + 4 = 7
(2 * 3) + 1 = 7
Summary
Congratulations! You have completed the Variadic Interfaces lab. You can practice more labs in LabEx to improve your skills.