Macros in Rust are a powerful feature that allows you to write code that writes other code. They enable you to define patterns that can be expanded into more complex code at compile time. This can help reduce repetition and improve code readability.
Key Differences Between Macros and Functions
- Expansion vs. Execution:
- Macros are expanded at compile time, meaning they generate code before the program runs.
- Functions are executed at runtime, meaning they perform actions when called during the program's execution.
- Input Types:
- Macros can accept a wider variety of input types, including syntax trees, which allows for more complex patterns.
- Functions require specific types for their parameters and cannot handle arbitrary code structures.
- Return Values:
- Macros do not have a return type in the same way functions do; they generate code that can produce various types based on the context.
- Functions have a defined return type and must return a value of that type.
Example
Here’s a simple example of a macro and a function in Rust:
In this example, say_hello!
is a macro that expands to a println!
statement, while say_hello_function
is a regular function that does the same thing but is called at runtime.