OpenGuild
Published on

Rust Practices with Rustlings - Macros

Chapter 21 - Macros

Exercise 1

macro_rules! my_macro {
    () => {
        println!("Check out my macro!");
    };
}

fn main() {
    my_macro();
}

Just add ! to call the macro

macro_rules! my_macro {
    () => {
        println!("Check out my macro!");
    };
}

fn main() {
    my_macro!();
}

Exercise 2

fn main() {
    my_macro!();
}

macro_rules! my_macro {
    () => {
        println!("Check out my macro!");
    };
}

We need to define the macro before calling it

macro_rules! my_macro {
    () => {
        println!("Check out my macro!");
    };
}

fn main() {
    my_macro!();
}

Exercise 3

// Make me compile, without taking the macro out of the module!

mod macros {
    macro_rules! my_macro {
        () => {
            println!("Check out my macro!");
        };
    }
}


fn main() {
    my_macro!();
}

We need to export the macro from the module

#[macro_export]
mod macros {
    macro_rules! my_macro {
        () => {
            println!("Check out my macro!");
        };
    }
}


fn main() {
    my_macro!();
}

Exercise 4

#[rustfmt::skip]
macro_rules! my_macro {
    () => {
        println!("Check out my macro!");
    }
    ($val:expr) => {
        println!("Look at this other macro: {}", $val);
    }
}

fn main() {
    my_macro!();
    my_macro!(7777);
}

Just add a comma after the first macro to separate it from the second one

#[rustfmt::skip]
macro_rules! my_macro {
    () => {
        println!("Check out my macro!");
    };
    ($val:expr) => {
        println!("Look at this other macro: {}", $val);
    }
}

fn main() {
    my_macro!();  
    my_macro!(7777);
}

Conclusion

The 21st chapter of Rustlings - Macros ends here.
TIL:

  • How to use declarative macros
  • Reed more about Macros in Rust here

Thanks for reading and please add comments below if you have any questions