在生成的函数中使用宏类型参数

Using a macro type argument inside a generated function

我正在尝试实现一个为结构实现 Add 特性的宏,如下所示:

macro_rules! implement_add {
    ($t:ty) => {
        impl std::ops::Add for $t {
            type Output = $t;
            fn add(self, rhs: $t) -> $t {
                $t(self.0 + rhs.0)        // error on this line
            }
        }
    }
}

pub struct Length(f64);

implement_add!(Length);

fn main() {}

但是,这会在指示的行上产生错误:

<anon>:6:17: 6:19 error: unexpected token: `Length`
<anon>:6                 $t(self.0 + rhs.0)        // error on this line
                         ^~

这对我来说毫无意义。特别是因为,如果我用 Length 替换那里的 $t,它编译得很好。我在宏中做错了什么吗?

游乐场:http://is.gd/EIEKub

您无意中发现了 Rust 类型系统的一小部分。 Length 是一个类型,但 Length() 是一个 函数 。它们存在于不同的命名空间中。

一种解决方法是扩展您的宏以接受类型 函数:

macro_rules! implement_add {
    ($t:ty, $c:ident) => {
        impl std::ops::Add for $t {
            type Output = $t;
            fn add(self, rhs: $t) -> $t {
                $c(self.0 + rhs.0)        // error on this line
            }
        }
    }
}

pub struct Length(f64);

implement_add!(Length, Length);

fn main() {}