I am going through Rust by Examples - Macros/DSL
The code shows:
macro_rules! calculate {
(eval $e:expr) => {{
{
let val: usize = $e; // Force types to be integers
println!("{} = {}", stringify!{$e}, val);
}
}};
}
fn main() {
calculate! {
eval 1 + 2 // hehehe `eval` is _not_ a Rust keyword!
}
calculate! {
eval (1 + 2) * (3 / 4)
}
}
Now I want my custom macro calculate
to return the calculated value. I tried with the following:
macro_rules! calculate {
(eval $e:expr) => {{
let val: usize = $e;
println!("{} = {}", stringify!{$e}, val);
val
}};
}
But it returns me error saying error[E0308]: mismatched types in val, expected type (), found type i32
.
How can I modify the above macro to return the calculated value? Thanks.
No, macros operate on syntax only.
macro_rules allows users to define syntax extension in a declarative way. We call such extensions "macros by example" or simply "macros". Each macro by example has a name, and one or more rules.
The most widely used form of macros in Rust is the declarative macro. These are also sometimes referred to as “macros by example,” “ macro_rules! macros,” or just plain “macros.” At their core, declarative macros allow you to write something similar to a Rust match expression.
Rust provides a powerful macro system that allows metaprogramming. As you've seen in previous chapters, macros look like functions, except that their name ends with a bang ! , but instead of generating a function call, macros are expanded into source code that gets compiled with the rest of the program.
I think I know what's wrong with it. In the original src code, it should end each calculate! {...}
macro call with a semi-colon.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With