Skip to content

Instantly share code, notes, and snippets.

@rpivo
Last active July 9, 2021 18:36
Show Gist options
  • Save rpivo/3eca6ce8a8841a1774e535352d51a7a1 to your computer and use it in GitHub Desktop.
Save rpivo/3eca6ce8a8841a1774e535352d51a7a1 to your computer and use it in GitHub Desktop.
Using Macros in Rust

Using Macros in Rust

Rust has certain abstractions called macros that are kind of like hooks in React (except that they don't necessarily have anything to do with state). Essentially, they abstract away other Rust code.

A macro is appended with an exclamation point !.

The println! code we use to print to the screen is a macro, as is vec!. They abstract away other code and allow us to write more simplified, clean code.

fn main() {
    let v = vec![1,2,3];
    for x in &v {
        println!("{}", x);
    }
}

Macros can be declared using the macro_rules! {} syntax. For instance vec! could be implemented like so (this is taken from the Rust Macros documentation):

macro_rules! vec {
    ( $( $x:expr ),* ) => {
        {
            let mut temp_vec = Vec::new();
            $(
                temp_vec.push($x);
            )*
            temp_vec
        }
    };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment