Destructure Structs In Match
Bind struct fields straight from match patterns with literals, @ bindings, and range checks, replacing field-by-field if chains.
Code
struct Order {
kind: String,
amount_cents: i64,
country: String,
}
// 金额单位固定为分(cents),避免浮点比较
fn review(order: &Order) -> &'static str {
match order {
// 字面量:金额为 0 直接判空单
Order { amount_cents: 0, .. } => "empty order",
// @ 绑定:金额落在 1..=100 的微小订单
Order { amount_cents: amt @ 1..=100, .. } => {
println!(" micro at {} cents", amt);
"micro order"
}
// 守卫:范围命中后再按国家细分
Order { amount_cents: 101..=5000, country } if country == "DE" => {
"domestic standard"
}
// 范围右开:大额订单转人工
Order { amount_cents: 5001.., .. } => "manual review",
Order { .. } => "standard",
}
}
fn main() {
let orders = [
Order { kind: "widget".into(), amount_cents: 0, country: "DE".into() },
Order { kind: "widget".into(), amount_cents: 45, country: "DE".into() },
Order { kind: "widget".into(), amount_cents: 2500, country: "DE".into() },
Order { kind: "widget".into(), amount_cents: 9900, country: "US".into() },
Order { kind: "widget".into(), amount_cents: 2000, country: "US".into() },
];
for order in &orders {
println!("{} -> {}", order.amount_cents, review(order));
}
}How it works
Destructure Structs In Match comes down to the functions review and main.
A single loop drives the file — for order in &orders. A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.
What to watch for
- No external packages — everything relies on the language’s built-in APIs.
Using it
Signature: fn review(order: &Order) -> &'static str
Running the file prints labeled results such as micro at — each operation’s effect is visible in the output.
Running the file executes main, which drives review in order.
Key statements
Order { amount_cents: 101..=5000, country } if country == "DE" => {
"domestic standard"
}
Order { amount_cents: amt @ 1..=100, .. } => {
println!(" micro at {} cents", amt);
"micro order"
}
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- What does Destructure Structs In Match print when run?
- Running the file directly is enough — expect labeled output lines such as `micro at`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.