Home:ALL Converter>Can macros expand array/vector into multiple indexed arguments?

Can macros expand array/vector into multiple indexed arguments?

Ask Time:2016-09-18T16:17:38         Author:ideasman42

Json Formatter

Is it possible to write a macro that expands an expression into multiple indexed arguments, which can be passed to a function or another macro?

See this simple self contained example.
The aim is to have unpack3 expand v into v[0], v[1], v[2].

macro_rules! elem {
    ($val:expr, $($var:expr), *) => {
        $($val == $var) || *
    }
}

// attempt to expand an array.
macro_rules! unpack3 {
    ($v:expr) => {
        $v[0], $v[1], $v[2]
    }
}

fn main() {
    let a = 2;
    let vars = [0, 1, 3];
    // works!
    if elem!(a, vars[0], vars[1], vars[2]) {
        println!("Found!");
    }
    // fails!
    if elem!(a, unpack3!(vars)) {
        println!("Found!");
    }
}

The second example fails, is it possible to make this work?

Possible solutions could include:

  • Changing use of macro grammar.
  • Using tuples, then expanding into arguments after.
  • Re-arranging the expressions to workaround macro constraints.

Note, this may be related to Escaping commas in macro output but don't think its a duplicate.

Author:ideasman42,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/39555539/can-macros-expand-array-vector-into-multiple-indexed-arguments
yy