3 Things that the Rust Standard Library should have…

Regarding yet the previous Macro and just for future memory and for others that could have the same problem.

If you use the @kaj Macro in the same file of the macro you can just do, like he did:

use std::collections::HashMap;

macro_rules! graph {
    [$($k:expr => $($v:expr),*);*] => {
        HashMap::from([
            $(($k, vec![ $($v),* ])),*
        ])
    }
}

let data2 = graph![
        0 => 1, 2;
        1 => 0, 2
];

but if you aren’t very versed in Macro implementations and access rules of Macros (like myself) and you have to put the Macro inside a file (utils.rs) and use it in other file (file_b.rs) and have a main.rs you need to do the following:

In utils.rs: Define the macro with the complete path do the HaspMap and export it as a pub in the crate.

macro_rules! graph {
    [$($k:expr => $($v:expr),*);*] => {
        ::std::collections::HashMap::from([
            $(($k, vec![ $($v),* ])),*
        ])
    }
}

pub(crate) use graph;

In main.rs: Declare that you are using all the macros from the module / file utils.rs.

// Macros
#[macro_use] mod utils;

and in file_b.rs: where you will be using it, you have to import it and use it like this.

use crate::utils::graph;

let data2 = graph![
        0 => 1, 2;
        1 => 0, 2
];

Thank you all.

Best regards,
João

1 Like