Macro write_struct

Source
macro_rules! write_struct {
    (public, $id_struct:ident, $vis_ids_types:expr) => { ... };
    (private, $id_struct:ident, $vis_ids_types:expr) => { ... };
}
Expand description

Write a struct type definition.

Makes the struct type available for import into the main crate via use_symbols.

§Parameters

  • public or private: whether to make the struct publicly visible after import with use_symbols.
  • $id: the name of the struct type, and the identifier by which it is referred when importing with use_symbols.
  • $vis_ids_types: The list of type &[(bool, I, T)] where the first component indicates visibility (true = public, false = private) of a field, I is the field’s identifier having type String or &str, and T is the field’s type: also having type String or &str.

§Notes

Before using write_struct! carefully consider all other approaches. Defining a struct in the usual way should be preferred when this is possible.

§Some use cases

  • Generation of wrapper APIs
  • Dependency injection, possibly in combination with write_statics!. Suppose that crate A depends on crate B. The build script of crate A generates certain constants C1, …, Cn. write_struct! is used to create a type T with fields that can be instantiated with the constants C1, …, Cn. Functions (say) in crate B can be called with a parameter of type T, allowing crate B access to the constants C1, …, Cn even though crate B is a dependency of crate A. If access to C1, …, Cn is desired in crate A or other crates depending on crate A, make a suitable call to write_statics! (or write_consts!) in crate A’s build script, followed by use_symbols!.

§Example

build.rs

fn main() {
   let foo_fields = vec![
       (true, "field_a", "Vec<u32>"),
       (true, "field_b", "String"),
       (false, "field_c", "(bool, Option<f32>)"),
       (false, "field_d", "i64"),
   ];
   rustifact::write_struct!(private, Foo, &foo_fields);
}

src/main.rs

rustifact::use_symbols!(Foo);
// The above line is equivalent to the declaration:
// struct Foo {
//     pub field_a: Vec<u32>,
//     pub field_b: String,
//     field_c: (bool, Option<f32>),
//     field_d: i64,
// }