Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created September 11, 2018 22:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rust-play/d723623277cd4c51c25e8d80cc48cd6f to your computer and use it in GitHub Desktop.
Save rust-play/d723623277cd4c51c25e8d80cc48cd6f to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
#[derive(Default)]
struct X {
a: String,
b: String,
c: String,
}
macro_rules! reject_empty {
($obj:ident, $first_field:tt, $($field:tt),*) => {
{
if $obj.$first_field.is_empty() {
Err(format!("{}.{} is empty", stringify!($obj), stringify!($first_field)))
}
$(
else if $obj.$field.is_empty() {
Err(format!("{}.{} is empty", stringify!($obj), stringify!($field)))
}
)*
else {
Ok(())
}
}
};
}
fn main() {
{
let x = X::default();
println!("Checked?: {:?}", reject_empty!(x, a, b));
}
{
let x = X { a: "One".to_string(), b: "".to_string(), c: "x".to_string() };
println!("Checked?: {:?}", reject_empty!(x, a, b));
}
{
let x = X { a: "One".to_string(), b: "Two".to_string(), c: "x".to_string() };
println!("Checked?: {:?}", reject_empty!(x, a, b));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment