Book: Chapter 1.2 - Reason for the `println!` macro

Created on 30 Jun 2017  路  4Comments  路  Source: rust-lang/book

The first paragraph that mentions macros describes their syntax and defers to an appendix for more information, but does not mention why someone might use a macro in Rust:

The second important part is println!. This is calling a Rust macro, which is how metaprogramming is done in Rust. If it were calling a function instead, it would look like this: println (without the !). We'll discuss Rust macros in more detail in Appendix E, but for now you just need to know that when you see a ! that means that you鈥檙e calling a macro instead of a normal function.

In situations like this, I always appreciate at least a hand-wavy explanation of why someone might do something like making println! a macro rather than a function. (In this case, so format strings can be processed at compile time, which normal functions can't do.) Otherwise I'm left unsure what to expect when dealing with these ! things- I only know something different is going on.

Most helpful comment

Another point from Reddit: macros can be variadic while functions cannot. This one is probably even more relevant to the println! example than the compile-time processing.

All 4 comments

A macro! can optionally evaluate its arguments.

Say one wanted to implement a function lazy_or and call it via

lazy_or(a(),b(),c())

Under eager evaluation, the functions a, b and c would all be evaluated before the call to lazy_or. But with a macro, the generated code can decide whether to call functions b or c.

Another point from Reddit: macros can be variadic while functions cannot. This one is probably even more relevant to the println! example than the compile-time processing.

Thanks! We actually haven't revised Chapter 1 heavily yet, I'll make sure we take care of this when we get there!

I would also appreciate at least a one sentence explanation. This is a pretty widely asked question:

https://www.reddit.com/r/rust/comments/4qor4o/newb_question_why_is_println_a_macro/
https://github.com/rust-lang/rust/issues/17190#issuecomment-55372530

meanwhile macros are not found in "common language features", they don't even have a chapter, they're delegated to an appendix which leads me to believe they're an advanced language feature. This makes me either google the question immediately or forget about it forever.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

drandreaskrueger picture drandreaskrueger  路  4Comments

ahowlett1965 picture ahowlett1965  路  5Comments

ctsa picture ctsa  路  3Comments

xStrom picture xStrom  路  3Comments

mikebenfield picture mikebenfield  路  3Comments