Create compile time string for lazy_static

I have some code where I need to store some mapping in a static configuration. For each string I want to store, I need another string that is just an extension of the first string.

lazy_static! {
    static ref A: BTreeMap<&'static str, usize> = {
        let mut v: BTreeMap<&str, usize> = BTreeMap::default();
        v.insert("hi", 1);
        v.insert("hi there", 2);
        v
    };
}

this works and I get:

vec: ["hi", "hi there"]

to avoid errors in the configuration, I tried to generate the second string with a macro

macro_rules! twice {
    ($var:expr) => {
        ($var, stringify!(format!("{} there", $var)))
    };
}

fn store<'a>(x: &'a str, y: &'a str, dest: &mut BTreeMap<&'a str, usize>) {
    dest.insert(x, 1);
    dest.insert(y, 2);
}

lazy_static! {
    static ref A: BTreeMap<&'static str, usize> = {
        let mut v: BTreeMap<&str, usize> = BTreeMap::default();
        let (a,b): (&str, &str) = twice!("hi");
        store(a, b, &mut v);
        v
    };
}

this type checks but gives undesired results because of my use of stringify:

vec: ["format ! ( \"{} there\" , \"hi\" )", "hi"]

I cannot figure out how to generate the desired strings with a macro and would need some advice.

here is the code sample in a playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=476fb6ba458f3243acd32840e9dc85ac

Looks like a task for the concat macro:

Playground

3 Likes

ok now I feel really stupid...but thanks so much! totally missed this! works like a charm!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.