struct-to-enum
Derive macros for generating enums corresponding to the fields of structs.
Overview
struct-to-enum provides two derive macros:
FieldName— generates a unit enum where each variant represents a field nameFieldType— generates an enum where each variant wraps the type of a struct field
Both macros support generics, field skipping, nesting (yes, you read that right) and custom derives/attributes on the generated enum.
Intended use-case is to generate enums from struct fields, enabling compile-time column filter validation for queries.
Usage
FieldName
Generates a unit enum {StructName}FieldName and a From<&Struct> impl that returns an array of variants in field order.
use FieldName;
// Generated:
// #[derive(Debug, PartialEq, Eq, Clone, Copy)]
// enum PointFieldName { X, Y }
let p = Point ;
let names: = .into;
assert_eq!;
Nested flattening
Mark a field with #[stem_name(nested)] to flatten its FieldName variants into the parent enum.
use FieldName;
// OuterFieldName has variants: A, X, Y
let o = Outer ;
let names: = .into;
assert_eq!;
FieldType
Generates a tuple-variant enum {StructName}FieldType and a From<Struct> impl that returns an array of variants holding the field values.
use FieldType;
// Generated:
// #[derive(Debug, Clone, PartialEq)]
// enum ConfigFieldType {
// Width(u32),
// Height(u32),
// }
let cfg = Config ;
let fields: = cfg.into;
Generics
Both macros handle generic structs with lifetime and type parameters.
use FieldType;
let p = Pair ;
let fields: = p.into;
Combining both macros
use ;
// RecordFieldName and RecordFieldType are both generated
Attributes
FieldName attributes
| Attribute | Location | Description |
|---|---|---|
#[stem_name_derive(...)] |
Struct | Override derives on the generated enum (default: Debug, PartialEq, Eq, Clone, Copy) |
#[stem_name_attr(...)] |
Struct | Add extra attributes to the generated enum |
#[stem_name(skip)] |
Field | Exclude this field from the generated enum |
#[stem_name(nested)] |
Field | Flatten the field's FieldName variants into the parent enum |
FieldType attributes
| Attribute | Location | Description |
|---|---|---|
#[stem_type_derive(...)] |
Struct | Specify derives for the generated enum |
#[stem_type_attr(...)] |
Struct | Add extra attributes to the generated enum |
#[stem_type(skip)] |
Field | Exclude this field from the generated enum |
Attribute aliases:
stem_name/ste_nameandstem_type/ste_typeare interchangeable.
Example: using with strum
use FieldType;
use VariantNames;
assert_eq!;
Inspired by:
License
Licensed under either of
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option