#field-name #struct-fields #proc-macro #macro #query #database

macro runtime-struct-field-names-as-array

Provides a procedural macro that generates an array of the field names of a named struct

1 unstable release

0.1.0 Mar 21, 2023

#829 in Procedural macros

Download history 3085/week @ 2023-12-11 1461/week @ 2023-12-18 37/week @ 2023-12-25 1259/week @ 2024-01-01 2412/week @ 2024-01-08 2396/week @ 2024-01-15 2212/week @ 2024-01-22 2550/week @ 2024-01-29 2175/week @ 2024-02-05 3445/week @ 2024-02-12 4860/week @ 2024-02-19 5638/week @ 2024-02-26 6859/week @ 2024-03-04 6795/week @ 2024-03-11 5605/week @ 2024-03-18 4499/week @ 2024-03-25

23,904 downloads per month

MIT license

8KB
85 lines

runtime-struct-field-names-as-array

crate-name at crates.io crate-name at docs.rs Rust

Provides the FieldNamesAsArray procedural macro. The macro adds the fn field_names_as_array() to the struct the macro is derived on. It contains the field names of the given struct, including the parents

Note: The macro can only be derived from named structs.

IMPORTANT This crate has a runtime overhead while it has limited options. If you do NOT intend to use it on a nested struct, you shall use this crate instead. See discussion

Table of Contents

Usage

You can derive the FieldNamesAsArray macro like this:

use runtime_struct_field_names_as_array::FieldNamesAsArray;

#[derive(FieldNamesAsArray)]
struct Foo {
  bar: String,
  baz: String,
  bat: String,
}

assert_eq!(Foo::field_names_as_array(), ["bar", "baz", "bat"]);

Attributes

The FieldNamesAsArray macro supports the field_names_as_array attribute. field_names_as_array can be applied to a field with only the flatten attribute

Container Attributes

Container attributes are global attributes that change the behavior of the whole field names array, rather than that of a single field.

Field Attributes

Field attributes can be added to the fields of a named struct and change the behavior of a single field.

Flatten

The flatten attribute will add the parent fields. Option struct are also supported. If the attribute is not added on a struct type, it will be considered as a regular field.

use runtime_struct_field_names_as_array::FieldNamesAsArray;

#[derive(FieldNamesAsArray)]
struct Parent {
  foo: String,
}

#[derive(FieldNamesAsArray)]
struct Foo {
  bar: String,
  baz: String,
  #[field_names_as_array(flatten)]
  parent: Parent,
  #[field_names_as_array(flatten)]
  parent_option: Option<Parent>,
  another_parent: Parent,
}

assert_eq!(Foo::field_names_as_array(), ["bar", "baz", "parent.foo", "parent_option.foo", "another_parent"]);

Dependencies

~0.3–0.8MB
~19K SLoC