HiveBrain v1.2.0
Get Started
← Back to all entries
gotcharustMajor

What is the difference between macros and functions in Rust?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
macrosfunctionsandbetweenthedifferencerustwhat

Problem

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?

Solution

Keep on reading the documentation, specifically the chapter on macros!

Rust functions vs Rust macros

Macros are executed at compile time. They generally expand into new pieces of code that the compiler will then need to further process.

Rust macros vs C macros

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

  • Can be distributed with the compiled code



  • Can be overloaded in argument counts



  • Can match on syntax patterns like braces or parenthesis or commas



  • Can require a repeated input pattern



  • Can be recursive



  • Operate at the syntax level, not the text level

Code Snippets

#define FIVE_TIMES(x) 5 * x

int main() {
    printf("%d\n", FIVE_TIMES(2 + 3));
    return 0;
}

Context

Stack Overflow Q#29871967, score: 71

Revisions (0)

No revisions yet.