【问题标题】:Rust macros: unit type?Rust 宏:单元类型?
【发布时间】:2020-08-10 02:31:46
【问题描述】:

以下宏:

macro_rules! generate_parse_expression_ast_data {
    ($lit:literal) => ();
}

enum Ast {
    Foo (generate_parse_expression_ast_data!("bar")),
}

给出这个错误:

error: macro expansion ends with an incomplete expression: expected type
 --> src/main.rs:6:10
  |
2 |     ($lit:literal) => ();
  |                       -- in this macro arm
...
6 |     Foo (generate_parse_expression_ast_data!("bar")),
  |          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |          |
  |          expected type
  |          this macro call doesn't expand to a type

error: aborting due to previous error

error: could not compile `playground`.

Playground link

我特别想将unit type 用于其中一些枚举情况,根据定义,它们应该是有效类型。我将如何做到这一点?

【问题讨论】:

  • 随机猜测(())
  • 试过了;它表现为Foo(())。这也许可行,但远非理想。
  • 但是单位类型 (),所以单位类型的变体是Foo(())。也许你想要一个空的类似元组的枚举?
  • 是的,理想的结果实际上只是Foo,但我可以接受Foo()

标签: rust macros


【解决方案1】:

看起来像known issue

我现在最好的建议是,除了发出一个大小为零的类型(如单元)之外,重新构造宏,以便它生成完整的变体。例如:

macro_rules! generate_parse_expression_ast_data {(
    enum $name:ident {
        $( $variant:ident($lit:literal), )+
    }
) => (
    enum $name {
        $( $variant(), )+
    }
)}

generate_parse_expression_ast_data! {
    enum Ast {
        Foo("bar"),
    }
}

【讨论】:

    猜你喜欢
    • 2017-03-11
    • 2023-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-10
    • 2022-09-25
    • 2016-03-16
    相关资源
    最近更新 更多