liveBook · Manning

DataStruct

As explained in Write Powerful Rust Macros

DataStruct is a syn syntax structure representing the parsed components and data of a Rust struct declaration.

DataStruct is syn’s parsed representation of a Rust struct’s declaration. It records the struct keyword, its fields, and an optional semicolon; the fields provide the useful structural data for a procedural macro. section 4.4

Reach it through DeriveInput.data: match the Data::Struct variant, then inspect DataStruct.fields. Matching Fields::Named yields named fields while ignoring unrelated properties with ..; other forms can be rejected explicitly. section 4.4

Extract named fields

let fields = match ast.data { syn::Data::Struct( syn::DataStruct { fields: syn::Fields::Named( syn::FieldsNamed { ref named, .. } ), .. } ) => named, _ => unimplemented!("only works for structs with named fields"), }; The resulting collection is Punctuated<Field, Token![,]>, so a macro can iterate over its Field values and generate corresponding output. section 4.4

pub struct DataStruct {
    pub struct_token: Token![struct],
    pub fields: Fields,
    pub semi_token: Option<Token![;]>,
}

Inspect DataStruct’s fields, struct token, and optional semicolon directly. section 4.4

How Write Powerful Rust Macros covers it

How deep it goes
Traces DeriveInput through Data and DataStruct to named Fields, but stops short of unnamed-field handling.
Examples
Uses a match expression to extract named fields and iterates over Punctuated<Field, Token![,]>.
What it assumes
Assumes Rust struct syntax, enum matching, and familiarity with procedural-macro parsing through DeriveInput.
What you can do after
Builds procedural macros that inspect named struct fields and generate output from their identifiers and types.
How it connects
Connects DeriveInput, Data, Fields, FieldsNamed, Punctuated, Field, and procedural 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.