@@ -4,6 +4,9 @@ Rust provides a powerful macro system that allows metaprogramming. As you've
4
4
seen in previous chapters, macros look like functions, except that their name
5
5
ends with a bang ` ! ` , but instead of generating a function call, macros are
6
6
expanded into source code that gets compiled with the rest of the program.
7
+ However, unlike macros in C and other languages, Rust macros are expanded into
8
+ abstract syntax trees, rather than string preprocessing, so you don't get
9
+ unexpected precedence bugs.
7
10
8
11
Macros are created using the ` macro_rules! ` macro.
9
12
@@ -21,4 +24,17 @@ fn main() {
21
24
// This call will expand into `println!("Hello");`
22
25
say_hello!()
23
26
}
24
- ```
27
+ ```
28
+
29
+ So why are macros useful?
30
+
31
+ 1 . Don't repeat yourself. There are many cases where you may need similar
32
+ functionality in multiple places but with different types. Often, writing a
33
+ macro is a useful wait to avoid repeating code. (More on this later)
34
+
35
+ 2 . Domain-specific languages. Macros allow you to define special syntax for a
36
+ specific purpose. (More on this later)
37
+
38
+ 3 . Variadic interfaces. Sometime you want to define an interface that takes a
39
+ variable number of arguments. An example is ` println! ` which could take any
40
+ number of arguments, depending on the format string!. (More on this later)
0 commit comments