【问题标题】:How to match a trait in a Rust macro?如何匹配 Rust 宏中的特征?
【发布时间】:2019-11-05 14:33:22
【问题描述】:

我的目标是作为输入特征类型。

my_test_macro!(Trait1, Trait2<Test1, Test2=Test3>)

到目前为止,我尝试的是编写这样的解析器。

$( $ty:ident < $( $N:ident $(: $b0:ident $(+$b:ident)* )? ),*  $($tname:ident=$ttype:ident),* > )+*

但它造成了局部歧义。

error: local ambiguity: multiple parsing options: built-in NTs ident ('N') or ident ('tname').

【问题讨论】:

    标签: rust rust-macros rust-decl-macros


    【解决方案1】:

    您可以使用typath metavariables,具体取决于您要执行的操作:

    macro_rules! my_test_macro {
        ($t1:ty, $t2:path) => {};
    }
    
    fn main() {
        my_test_macro!(Trait1, Trait2<Test1, Test2 = Test3>);
    }
    

    另见:

    【讨论】:

    • 直到您可以在需要特征的地方使用ty 变量:playground。我本来预计会失败,就像impl dyn Trait for i32 {} 那样。我想知道当删除裸特征语法时这是否会改变。
    • 是的,我认为这是 SomeTraitName 的二元性,要么是一个特征 要么 是一个允许这样做的类型。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-16
    • 2019-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多