【问题标题】:How are multiple trait bounds expanded in a rust macro?如何在 rust 宏中扩展多个特征边界?
【发布时间】:2020-07-15 17:15:59
【问题描述】:

我有一些与下面的 sn-p 等效的 Rust 代码,但无法编译

trait A {}
trait B {}

macro_rules! implement {
    ( $type:ty ) => {
        struct C<T: $type> { // <-- Changing "$type" to "A + B" compiles
            t: T,
        }
    }   
}

implement!(A + B); 

fn main() {}

用rustc 1.44.1 编译它会产生:

error: expected one of `!`, `(`, `,`, `=`, `>`, `?`, `for`, lifetime, or path, found `A + B`

将$type 替换为A + B 进行编译。

我的问题是为什么它不能按原样编译,如何改变它?

(注意:Rust 有点新,我相信有更简单的方法可以解决这个问题,任何建议都会有所帮助)

【问题讨论】:

    标签: generics rust compiler-errors compilation macros


    【解决方案1】:

    ty 宏参数类型有不同的用途:它是type,而不是bound。您可以为此使用多个令牌:

    macro_rules! implement {
        ( $($token:tt)* ) => {
            struct C<T: $($token)*> {
                t: T,
            }
        }
    }
    

    【讨论】:

    猜你喜欢
    • 2020-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多