File tree Expand file tree Collapse file tree 2 files changed +56
-9
lines changed
programiz/attempt-02/hello_world/src Expand file tree Collapse file tree 2 files changed +56
-9
lines changed Original file line number Diff line number Diff line change @@ -57,3 +57,52 @@ cargo run
5757``` bash
5858Hello, 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+ ```
Original file line number Diff line number Diff line change 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
109fn 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}
You can’t perform that action at this time.
0 commit comments