liveBook · Manning

Syn data

As explained in Write Powerful Rust Macros

Data is a syn enum representing whether a parsed input contains a struct, enum, or union.

In a parsed derive-macro input, `ast.data` holds the declaration's data shape. `syn::Data` is an enum with `Struct`, `Enum`, and `Union` variants, letting macro code branch on the target kind. section 4.4

pub enum Data {
    Struct(DataStruct),    #1
    Enum(DataEnum),       
    Union(DataUnion),    
}

Inspect the three `syn::Data` variants and their nested types. section 4.4

Extracting named struct fields

Match the `Struct` variant, descend through `DataStruct` and `FieldsNamed`, and reject other shapes when the macro only supports named-field structs: `let fields = match ast.data { Struct(DataStruct { fields: Named(FieldsNamed { ref named, .. }), .. }) => named, _ => unimplemented!("only works for structs with named fields"), };` The resulting fields can then be iterated to generate public declarations. section 4.4

How Write Powerful Rust Macros covers it

How deep it goes
Defines three variants and descends into named struct fields, while deferring unnamed-field handling.
Examples
Uses an attribute macro that matches named fields and generates public field declarations.
What it assumes
Assumes Rust pattern matching and derive-macro parsing; teaches where struct fields reside.
What you can do after
Apply it via syn by matching parsed DeriveInput data and extracting named fields.
How it connects
Connects DeriveInput, DataStruct, Fields, FieldsNamed, and derive macros.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Write Powerful Rust Macros. The section links point to the parts of the book it draws on.