一次实现多个新类型的特征

时间:2014-10-12 17:12:16

标签: rust

我有一堆newtypes基本上只是包装String对象:

#[deriving(Show)]
struct IS(pub String);
#[deriving(Show)]
struct HD(pub String);
#[deriving(Show)]
struct EI(pub String);
#[deriving(Show)]
struct RP(pub String);
#[deriving(Show)]
struct PL(pub String);

现在,#[deriving(Show)]为输出生成以下内容:EI(MyStringHere),我只想输出MyStringHere。实现Show明确有效,但有没有办法同时为所有这些新类型实现它?

1 个答案:

答案 0 :(得分:2)

语言本身没有这种方式,但您可以轻松地使用宏:

#![feature(macro_rules)]

struct IS(pub String);
struct HD(pub String);
struct EI(pub String);
struct RP(pub String);
struct PL(pub String);

macro_rules! newtype_show(
    ($($t:ty),+) => ($(
        impl ::std::fmt::Show for $t {
            fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                write!(f, "{}", self.0[])
            }
        }
    )+)
)

newtype_show!(IS, HD, EI, RP, PL)

fn main() {
    let hd = HD("abcd".to_string());
    println!("{}", hd);
}

(试试here