Skip to content

Commit 895d4a4

Browse files
committed
Add Macro example
1 parent 6c69066 commit 895d4a4

File tree

2 files changed

+70
-14
lines changed

2 files changed

+70
-14
lines changed

documentation2/B08-Macro.md

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# [Macro](https://www.programiz.com/rust/macro)
2+
3+
A macro in Rust is a piece of code that generates another piece of code.
4+
5+
Macros generate code based on input, simplify repetitive patterns, and make code more concise.
6+
7+
Rust macro simply allows us to write code that writes more code which is also known as meta programming. Macros are used extensively in Rust.
8+
9+
Some of the popular Rust macros are `println!`, `vec!` and `panic!`.
10+
11+
____
12+
13+
## Creating a Macro in Rust
14+
15+
We can create a macro using the `macro_rules!` macro. It might be surprising but yes we use a macro to create a macro.
16+
17+
The `macro_rules!` macro has a special syntax.
18+
19+
```rust
20+
macro_rules! macro_name {
21+
(...) => {...}
22+
// more match rules
23+
}
24+
```
25+
26+
Here, `() => {}` is the entry for a macro rule. We can have many rules to match for in a single macro.
27+
28+
Let's look at an example of a simple macro that defines a new function to print "Hello, World!".
29+
30+
```rust
31+
// A simple macro named `hello_world`
32+
macro_rules! hello_world {
33+
// `()` indicates that the macro takes no argument
34+
() => {
35+
// The macro will expand into the contents of this block
36+
println!("Hello, World!")
37+
};
38+
}
39+
40+
fn main() {
41+
// Call the hello_world macro
42+
// This call will expand into `println!("Hello, World!");`
43+
hello_world!()
44+
}
45+
```
46+
47+
```bash
48+
cargo build
49+
```
50+
51+
```bash
52+
cargo run
53+
```
54+
55+
### Output
56+
57+
```bash
58+
Hello, World!
59+
```
Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,14 @@
1-
use std::fs::OpenOptions;
2-
use std::io::Write;
1+
// A simple macro named `hello_world`
2+
macro_rules! hello_world {
3+
// `()` indicates that the macro takes no argument
4+
() => {
5+
// The macro will expand into the contents of this block
6+
println!("Hello, World!")
7+
};
8+
}
39

410
fn main() {
5-
// Open a file with append option
6-
let mut data_file = OpenOptions::new()
7-
.append(true)
8-
.open("data.txt")
9-
.expect("cannot open file");
10-
11-
// Write to a file
12-
data_file
13-
.write("I am learning Rust!".as_bytes())
14-
.expect("write failed");
15-
16-
println!("Appended content to a file");
11+
// Call the hello_world macro
12+
// This call will expand into `println!("Hello, World!");`
13+
hello_world!()
1714
}

0 commit comments

Comments
 (0)