Created
September 13, 2019 22:01
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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