2

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?

1 Answer 1

2

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)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.