Advertisement
Guest User

Untitled

a guest
Nov 9th, 2020
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.44 KB | None | 0 0
  1. macro_rules! opt_field_struct {
  2.     (
  3.         $(#[$attr:meta])*
  4.         $visibility:vis struct $struct_name:ident {
  5.             $(
  6.                 $(#[$field_attr:meta])*
  7.                 $field_visibility:vis $field_name:ident: $field_ty:ty,
  8.             )*
  9.         }
  10.     ) => {
  11.         $(#[$attr])*
  12.         $visibility struct $struct_name {
  13.             $(
  14.                 $(#[$field_attr])*
  15.                 $field_visibility $field_name: $field_ty,
  16.             )*
  17.         }
  18.  
  19.         impl $struct_name {
  20.             $visibility fn is_complete(&self) -> bool {
  21.                 $(
  22.                     if self.$field_name.is_none() {
  23.                         return false
  24.                     }
  25.                 )*
  26.  
  27.  
  28.                 true
  29.             }
  30.         }
  31.     };
  32. }
  33.  
  34. opt_field_struct!(
  35.     struct MyStruct {
  36.         pub optional_field: Option<usize>,
  37.         another_optional_field: Option<String>,
  38.         and_another: Option<String>,
  39.     }
  40. );
  41.  
  42. // Generated code:
  43. struct MyStruct {
  44.     pub optional_field: Option<usize>,
  45.     another_optional_field: Option<String>,
  46.     and_another: Option<String>,
  47. }
  48. impl MyStruct {
  49.     fn is_complete(&self) -> bool {
  50.         if self.optional_field.is_none() {
  51.             return false;
  52.         }
  53.         if self.another_optional_field.is_none() {
  54.             return false;
  55.         }
  56.         if self.and_another.is_none() {
  57.             return false;
  58.         }
  59.         true
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement