Creating an Enumeration Inside a Macro

Is it possible to build correspondence inside a Rust macro using fields that are defined as macro parameters? I tried this:

macro_rules! build {
    ($($case:ty),*) => { enum Test { $($case),* } };
}

fn main() {
    build!{ Foo(i32), Bar(i32, i32) };
}

But he fails with error: expected ident, found 'Foo(i32)'

Note that if the fields are defined inside the enumeration, there is no problem:

macro_rules! build {
    ($($case:ty),*) => { enum Test { Foo(i32), Bar(i32, i32) } };
}

fn main() {
    build!{ Foo(i32), Bar(i32, i32) };
}

It also works if my macro accepts only simple fields:

macro_rules! build {
    ($($case:ident),*) => { enum Test { $($case),* } };
}

fn main() {
    build!{ Foo, Bar };
}

But I could not get it to work in the general case.

+4
source share
1 answer

It is absolutely possible, but you combine completely unrelated concepts.

- $case:ty , $case - , , $case . ; , , () , .

, , , , .

- $case:variant. , . - - , SO, . , TT " ".

, , , . . - :

macro_rules! build {
    ($($body:tt)*) => {
        as_item! {
            enum Test { $($body)* }
        }
    };
}

macro_rules! as_item {
    ($i:item) => { $i };
}

fn main() {
    build!{ Foo, Bar };
}

( , as_item! AST ( " ").)

, build! enum , .

- , , , , , .

+8

All Articles