Search code examples
ruststaticmutablerust-proc-macros

Create a vector with macro iterator syntax


How can I create a new vector with the iterator Rust macro syntax?

I am trying this:

unsafe { 
    MUT_STATIC_VAR = vec![
       #(#my_outher_vector_data)*,
    ];
}

Full explanation: I am trying to reasign data that I write in one mut static var of type: Vec when the macro it's spanded at compile time. When I try to retrieve the data at runtime, the global it's empty, so I am rewiring the data that I want in main().

Recap. I am just want to assign the content of one vector to another, but neither array or Vec<T> implements ToTokens.

Compiler error:

`main` function not found in crate `my_crate`

Thanks


Solution

  • To initialize the content, Iterators are able to use macro #(#...)*, syntax.

    let other_as_iter = my_outher_vector_data.iter();
    
    
    quote {
        unsafe { 
            MUT_STATIC_VAR = vec![
               #(#other_as_iter)*,
            ];
        }
    }