Tour · 12 of 18
Derivation
The program on the right reads an order from JSON and compares it.
#@derive
@derive(Eq, Debug, Serialize, Deserialize)
struct Order:
id: string
total_cents: i32@derive asks for standard implementations that follow the fields. The
compiler describes each field to the derivation code. You only name the
behavior you want.
#The derived behavior
match decode::[Order](text):
.Ok(order) =>
expected := Order { id: "A-1042", total_cents: 2500 }
println("same: ${order == expected}")
println(debug(order))
.Err(error) => println("decode failed: $error")Eqgives==, as inorder == expected.Debuggivesdebug(order), which describes the fields.SerializeandDeserializeconnect the type to JSON, sodecode::[Order]can read it.
Run it. The decoded order equals the literal, so it prints same: true.
Then it prints the order's debug text.
Try it: change @derive(Eq, Debug, Serialize, Deserialize) to @derive(Eq, Serialize, Deserialize) and press Run.
Run: Ctrl+Enter · Pages: Alt+← Alt+→