Skip to content

Commit e49031e

Browse files
committed
Add macro with argument file Build Run Copy Output to document
1 parent 895d4a4 commit e49031e

File tree

2 files changed

+56
-9
lines changed

2 files changed

+56
-9
lines changed

documentation2/B08-Macro.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,3 +57,52 @@ cargo run
5757
```bash
5858
Hello, World!
5959
```
60+
61+
In this example, we create a macro named `hello_world`. The macro definition has one rule to match which is:
62+
63+
```rust
64+
() => {
65+
println!("Hello, World!");
66+
};
67+
```
68+
69+
To call the macro we use the `hello_world!()` call in the `main()` function.
70+
71+
The macro will replace the `hello_world!()` call with the code defined in the macro definition i.e. `println!("Hello, World!)`.
72+
73+
____
74+
75+
## Creating a Macro with Arguments in Rust
76+
77+
Macros can also take arguments, which allows us to customize the code that it generates based on different inputs.
78+
79+
For example, here's a macro that defines a function to print a custom message:
80+
81+
```rust
82+
// A macro named `print_message`
83+
macro_rules! print_message {
84+
// Match rule that takes an argument expression
85+
($message:expr) => {
86+
println!("{}", $message)
87+
};
88+
}
89+
90+
fn main() {
91+
// Call the macro with an argument
92+
print_message!("I am learning Rust!");
93+
}
94+
```
95+
96+
```bash
97+
cargo build
98+
```
99+
100+
```bash
101+
cargo run
102+
```
103+
104+
### Output
105+
106+
```bash
107+
I am learning Rust!
108+
```
Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,12 @@
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!")
1+
// A macro named `print_message`
2+
macro_rules! print_message {
3+
// Match rule that takes an argument expression
4+
($message:expr) => {
5+
println!("{}", $message)
76
};
87
}
98

109
fn main() {
11-
// Call the hello_world macro
12-
// This call will expand into `println!("Hello, World!");`
13-
hello_world!()
10+
// Call the macro with an argument
11+
print_message!("I am learning Rust!");
1412
}

0 commit comments

Comments
 (0)