Filling vec in macro

Hello

I feel there is something simple to do this, but I can't find it, and, I'm getting in the wrong road I feel.

I would need to write something like vec![&self.param1, &self.param2, ....] in a macro.

macro! { param1, param2, param3} ...... => 
fn aFun(&mut self) { vec![&self.param1 .....] }

How could we achieve that ?

Do you intend for the macro call to create a function that returns a Vec with references to the params?

yes exactly :slight_smile:

You can look at the implementation of the vec macro. You can implement your version in a very similar way:

macro_rules! vec_of_refs {
    () => (
        vec![]
    );
    ($elem:expr; $n:expr) => (
        vec![&$elem; $n]
    );
    ($($x:expr),+ $(,)?) => (
        vec![$(&$x),+]
    );
}

Playground

The Little Book of Rust Macros is a great resource for learning about Rust's Macro-By-Example system.

1 Like

You can do something like this if you want the macro to generate a function which returns the vec. This only works if all the values have the same type thats known ahead of time, since Vec must all have the same type.

Playground Link

Thanks for the link to The Little Book of Rust Macros. I'd never come across that before.

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