logoalt Hacker News

GMoromisatolast Sunday at 7:09 PM2 repliesview on HN

I'm curious here, because I don't know Rust. What's the difference between a macro and a function call from the caller's perspective? Do I (as the caller) need to know I'm calling a macro? Why?

Why is println! a macro when it's a function in almost all other languages?


Replies

wrslast Sunday at 7:29 PM

GCC can type-check printf (matching format string to arguments) because the compiler doesn’t just treat it like a function. But that requires special-case code in the C compiler itself that is basically opaque magic.

Rust doesn’t need that, it’s mostly Rust code in the standard library, with only a small bit of compiler magic triggered by the macro. (Println! isn’t the best example because it does have that small bit of magic; most macros are just plain Rust code.)

Here’s a very impressive set of macros that I use daily. [0] This lets you do “printf logging” on an embedded device, with the human readable strings automatically pulled out into a separate section of the ELF file so the actual log stream data is tiny.

I did a similar thing for C a while ago, as a pre- and post- build step. It worked, but much less well, and was a maintenance nightmare.

Edit: and yeah, I think you do need to know you’re calling a macro, because macros aren’t limited to “normal” syntax or semantics. The ! is a signal that you’re escaping the usual bounds of the language. Like this. [1]

[0] https://defmt.ferrous-systems.com/macros

[1] https://docs.embassy.dev/embassy-stm32/git/stm32f301k6/macro...

syklemillast Monday at 11:56 AM

I think another macro, `json!()` works better as an example for that: inside the `json!()` you write something very similar to actual JSON. So when you see a `!` you know that there might be something out-of-the-ordinary following: https://docs.rs/serde_json/latest/serde_json/macro.json.html

Incidentally it also means that formatters like `rustfmt` won't apply the usual rules. For the macros that don't really deviate from ordinary Rust syntax, that can be a bit annoying.