Skip to main content
A struct pattern is a destructuring mechanism in Rust used to unpack and bind the internal fields of a struct to local variables during pattern matching. It allows for precise extraction of data and structural validation within constructs such as match, let, if let, and function signatures.

Basic Destructuring and Binding

To destructure a struct, the pattern must match the exact name of the struct. You map the struct’s fields to new local variables using the field_name: variable_name syntax.

Field Shorthand

If the local variable you are binding to has the exact same name as the struct field, Rust permits a shorthand syntax where you omit the : variable_name declaration.

Binding Modes

Struct patterns support binding modes to modify how fields are extracted. By default, fields are moved or copied (depending on Copy semantics). You can use mut, ref, and ref mut to alter this behavior per field.

Function Signatures

Struct patterns can be applied directly within function parameter lists. This allows a function to accept a struct and immediately destructure its fields into local variables for the function body.

Ignoring Fields with the Rest Pattern

When a struct contains multiple fields but only a subset is required for the binding, the rest pattern (..) is used to explicitly ignore all unlisted fields. This prevents compiler errors regarding exhaustive matching.

Literal and Wildcard Matching

Struct patterns can evaluate the inner values of the fields directly. You can match against specific literals or use the wildcard (_) to ignore a specific field without using the rest pattern.

Nested Struct Patterns

Struct patterns can be nested to destructure complex, hierarchical data types in a single statement. The syntax cascades inward, matching the outer struct and then immediately destructuring the inner struct.

Destructuring Enums with Struct Variants

Struct patterns are also applied when matching against enum variants that are defined as struct-like variants. The syntax behaves identically to standard struct destructuring.
Tired of Poor Rust Skills? Fix That With Deep Grasping!Learn More