Skip to content

Instantly share code, notes, and snippets.

@cfsamson
Created September 13, 2019 22:01
Show Gist options
  • Save cfsamson/39f452251e5390c9ca2bf23b73f222fb to your computer and use it in GitHub Desktop.
Save cfsamson/39f452251e5390c9ca2bf23b73f222fb to your computer and use it in GitHub Desktop.
A macro to ease the concatination of meny optional string fields like in large structs representing json objects that have many possibly empty fields
use std::fmt;
macro_rules! txt_concat {
($($model: expr), *) => {{
let mut s = String::new();
$(
if let Some(t) = $model {
s.push_str(&t);
s.push(' ');
}
)*
s
}};
}
struct Invoice {
supplier_name: Option<String>,
supplier_id: Option<String>,
department: Option<String>,
text: Option<String>,
}
impl Invoice {
fn new(s_name: &str, s_id: &str, dept: &str, text: &str) -> Self {
Invoice {
supplier_name: Some(s_name.to_string()),
supplier_id: Some(s_id.to_string()),
department: Some(dept.to_string()),
text: Some(text.to_string()),
}
}
}
impl fmt::Display for Invoice {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let text = txt_concat!(
&self.supplier_name,
&self.supplier_id,
&self.department,
&self.text
);
write!(f, "{}", text)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment