Nemanja Boric
Nemanja Boric

Reputation: 22157

Implementing trait for multiple newtypes at once

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

Answers (1)

Vladimir Matveev
Vladimir Matveev

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

Related Questions