Reputation: 22157
I have a bunch newtypes that are basically just wrapping String
object:
#[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);
Now, #[deriving(Show)]
, produces the following for the output: EI(MyStringHere)
, and I would like just to output MyStringHere
. Implementing Show
explicitly works, but is there any way to implement it for all these newtypes at once?
Upvotes: 2
Views: 153
Reputation: 127801
There is no such way in the language itself, but you can employ macros for this easily:
#![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);
}
(try it here)
Upvotes: 2