简体   繁体   English

一个Rust宏可以生成多个声明吗?

[英]Can a single Rust macro generate multiple declarations?

As a learning exercise I am trying to write a macro that generates two declarations. 作为学习练习,我试图编写一个生成两个声明的宏。 In this example I am trying to write a macro that generates declarations for an enum with a single field and a static vector that contains an instance of that field: 在此示例中,我尝试编写一个宏,该宏为具有单个字段和包含该字段实例的静态向量的枚举生成声明:

#![feature(macro_rules)]
macro_rules! create_enum(
        ( $enum_name : ident , $a_field_name : ident ) => 
        {
            enum $enum_name { $a_field_name };
            static foovec: [$enum_name,..1] = [ $a_field_name ]; 
        };
)

create_enum! (Direction , NORTH)

I get the error: 我得到错误:

enums.rs:5:36: 5:37 error: macro expansion ignores token `;` and any following
enums.rs:5              enum $enum_name { $a_field_name };

I have tried maybe 10 punctuation variations without success, so I am starting to wonder if this just isn't supported by rust macros. 我尝试了10种标点符号变化,但均未成功,因此我开始怀疑rust宏是否不支持这种方法。

enum declarations don't need a ; enum声明不需要; at the end. 在末尾。

This works for me: 这对我有用:

#![feature(macro_rules)]
macro_rules! create_enum(
        ( $enum_name : ident , $a_field_name : ident ) => 
        {
            enum $enum_name { $a_field_name }
            static foovec: [$enum_name,..1] = [ $a_field_name ]; 
        };
)

create_enum! (Direction , NORTH)

Demo: http://is.gd/JxMAb1 演示: http//is.gd/JxMAb1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM