Quoted from the Rust blog:
One last thing to mention: Rust’s macros are significantly different from C macros, if you’ve used those
What is the difference between macros and function in Rust? How is it different from C?
Macros have the distinct advantage of being more efficient (and faster) than functions, because their corresponding code is inserted directly into your source code at the point where the macro is called. There is no overhead involved in using a macro like there is in placing a call to a function.
Functions are the building blocks of readable, maintainable, and reusable code. A function is a set of statements to perform a specific task. Functions organize the program into logical blocks of code.
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.
Keep on reading the documentation, specifically the chapter on macros!
Macros are executed at compile time. They generally expand into new pieces of code that the compiler will then need to further process.
The biggest difference to me is that Rust macros are hygenic. The book has an example that explains what hygiene prevents, and also says:
Each macro expansion happens in a distinct ‘syntax context’, and each variable is tagged with the syntax context where it was introduced.
It uses this example:
For example, this C program prints 13 instead of the expected 25.
#define FIVE_TIMES(x) 5 * x int main() { printf("%d\n", FIVE_TIMES(2 + 3)); return 0; }
Beyond that, Rust macros
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