Refactor struct fn with macro?

I have the below functions that are the same across several rust struct implementations. I'm quite confused how to refactor these two functions into macros or if I can.

Any pointers would be greatly appreciated. thanks

// convert struct to json
fn to_log(&self) -> String {
    match serde_json::to_string(&self) {
        Ok(l) => return l,
        _ => return "".into()
    };
}

// convert struct to json and report it out
pub fn report_log(&self) {
    if !ARGS.flag_ip.eq("NONE") {
        let socket = format!("{}:{}", ARGS.flag_ip, ARGS.flag_port);
        let mut stream = TcpStream::connect(socket)
            .expect("Could not connect to server");
        stream.write(format!("{}{}", self.to_log(), "\n")
            .as_bytes())
            .expect("Failed to write to server");
    } else {
        println!("{}", self.to_log());
    }
}

There is no need for a macro, here a(n extension) trait suffices just fine:

trait Loggable : Serialize {
    /// convert struct to json
    fn to_log (self: &'_ Self)
      -> Str
    {
        ::serde_json::to_string(&self)
            .ok()
            .map_or("<failed to serialize>".into(), Into::into)
    }
    
    /// convert struct to json and report it out
    fn report_log (self: &'_ Self)
    {
        if !ARGS.flag_ip.eq("NONE") {
            let socket = format!("{}:{}", ARGS.flag_ip, ARGS.flag_port);
            let mut stream =
                ::std::net::TcpStream::connect(socket)
                    .expect("Could not connect to server")
            ;
            use ::std::io::Write;
            writeln!(stream, "{}", self.to_log())
                .expect("Failed to write to server")
            ;
        } else {
            eprintln!("{}", self.to_log());
        }
    }
}
impl<T : ?Sized + Serialize> Loggable for T {}

// where
type Str = ::std::borrow::Cow<'static, str>;
2 Likes

Nice and thank you. Haven't worked with traits yet in Rust so something new to learn. Thanks again for the excellent help.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.