我有一堆新类型,基本上只是包装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显式工作,但是有什么方法可以同时为所有这些新类型实现它吗?
发布于 2014-10-12 17:50:17
在语言本身中没有这样的方法,但是您可以很容易地使用宏:
#![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);
}(试试吧,这里)
https://stackoverflow.com/questions/26327778
复制相似问题