How to apply my trait on multiple struct without code duplication?

Hi everyone !

In my app I have a lot of structs wrapped into bitflags! and I need to impl serde::Serialize on each. But the code is same:

impl Serialize for MovementFlags {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut str_flags = String::new();
        let mut first = true;
        for flag in self.iter() {
            if first {
                first = false;
            } else {
                str_flags += " | ";
            }
            str_flags += &format!("{:?}", flag);
        }
        serializer.serialize_str(&str_flags)
    }
}

This is the sandbox to test: Rust Playground

Could somebody advice how can I avoid code duplication when implementing this trait on each new struct ?

Macros.

macro_rules! impl_serialize_for_flags {
    ($flag_ty:ident) => {
        impl Serialize for $flag_ty {
            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
            where
                S: Serializer,
            {
                let mut str_flags = String::new();
                let mut first = true;
                for flag in self.iter() {
                    if first {
                        first = false;
                    } else {
                        str_flags += " | ";
                    }
                    str_flags += &format!("{:?}", flag);
                }
                serializer.serialize_str(&str_flags)
            }
        }
    };
}

impl_serialize_for_flags!(MovementFlags);
2 Likes

Thank you !

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.