我正在尝试实现一个实现结构的Add trait的宏,如下所示:
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() {}
Run Code Online (Sandbox Code Playgroud)
但是,这会在指定的行上出错:
<anon>:6:17: 6:19 error: unexpected token: `Length`
<anon>:6 $t(self.0 + rhs.0) // error on this line
^~
Run Code Online (Sandbox Code Playgroud)
这对我来说毫无意义.特别是因为,如果我更换$t与有Length,它编译罚款.我在宏观中做错了吗?
游乐场: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() {}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
299 次 |
| 最近记录: |