首页 > 解决方案 > 如何在 rust 宏中扩展多个特征边界?

问题描述

我有一些与下面的代码片段等效的 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`

同时替换$typeA + B编译。

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

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

标签: genericsrustcompiler-errorscompilationmacros

解决方案


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

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

推荐阅读