Since we have macros, why use functions at all?

I'm just delving in to Rust this week (got a tetanus shot just in case), and I came across this post on macros: [newbie ?] Why macros vs. functions??

If macros are superior to functions, why use functions at all, and why were functions included in the language?


Right?! But my question is: since we already have macros, do we really need generic types?

Macros expand to code (or more accurately, entries on the parse tree). This means, that among other things:

  • Debug binaries become freaking huge, as all functions are manually inlined regardless of suitability to inlining
  • For the same reason, compilation takes forever and is a memory hog, as the compiler has to navigate a giant, extremely deep parse tree
  • Recursive functions are now impossible, as trying to expand such a thing results in an infinite recursive descent

Functions end up as a section of code that can be jumped to with register and stack parameters in hand (unless they are inlined automatically by compiler optimizations), so they have none of these problems.


I don't think there was any need to be snarky. He or she may be too new to programming to appreciate what's obvious to you and me.


With great power comes great responsibility. Macros are necessary and a usefull addition to a language, but their power lies in "being able to do what functions can't", and at least my attitude is "there's a reason functions can't do it". Namely, control flow and environment (the second is where closures come in, and that's a reason why you don't structure your code using closures instead of functions). Using macros it's hard to reason about what-does-what, where functions provide very clear-cut possibilities: after the function is done, the next line after the call will be executed (if nothing panicked, that is), and everything it can touch is global stuff or what you passed it. This is very analogous to why you don't want too many all-global variables, and to using a reference instead of a mutable reference, if possible. Less power is more, because you as a human can reason about it.

Try to read C code where macros don't follow the "macros are all caps" convention, but are named like functions instead. It's a total nightmare, and while Rusts macros alleviate quite some problems of C macros, some of that is just inherent to text transformations.


Thanks for the great answers. I'm new enough that i don't fully grok all that, but it gives me something to research.

@jethrogb Yeah, i'm sort of new at all this. I tried learning C 35 years ago, and got bogged down trying to understand pointers at 10 years old. Now, after years of getting sucked in first by VB for a decade (bleh), and now web stuff with php, i'm looking to get to something closer to the metal and work with ambisonic libraries.

So, it's not Greek to me, it;s more like Latin :"P.