@derive
@derive: generating show, eq, order, hash and clone (and JSON reading and writing) for a struct, enum or obj, what each one does, and when it is refused.
@derive(name, ...) before a struct, enum or obj writes the interface implementations for you, field by field and case by case.
@derive(show, eq, order, hash, clone)
struct point {
x: int
y: int
}
fn main() {
const a = point { x: 1, y: 2 }
const b = a.clone()
print(a, a == b, a < point { x: 1, y: 3 }, a.hash() == b.hash())
}point { x: 1, y: 2 } true true trueWhat each name generates
| Name | Gives you | Page |
|---|---|---|
show | print(x) and "#x"; shows field names for structs and case names for enums. | show |
eq | ==, != and .eq(); compares field by field. | eq |
order | <, >, <=, >=, sort!, min, max; compares fields first to last. | order |
hash | Use as a map key or set member; needs eq too. | hash |
clone | copy x and .clone() for an obj. | clone |
fromJson, toJson | Typed JSON reading and writing; needs import std.json. | typed JSON |
A plain struct or enum made of comparable, copyable fields already supports == and copy; derive what you need beyond that. An obj has none of them until you derive or write the impl.
Deriving on enums
@derive(show, eq)
enum res {
good(int)
bad(msg: string)
empty
}
fn main() {
print(res.good(3), res.bad(msg: "no"), res.empty == res.empty)
}good(3) bad("no") trueDeriving on obj
@derive(eq, hash)
obj point {
x: int
y: int
}
fn main() {
var seen: set<point> = set {}
seen.insert!(point { x: 1, y: 2 })
print(seen.contains(point { x: 1, y: 2 }), seen.contains(point { x: 2, y: 1 }), seen.len())
}true false 1When it cannot be derived
Every field must itself support the interface. A field that cannot be stored, such as a function value, is refused by the type checker:
main:2:25: error: a field cannot hold a view such as `str` or a function value; use `string`, or `box<fn ...>` for a functionWithout the derive, using the operation is an error that tells you the fix, for example a` cannot be ordered with `<`: it does not provide `order`; write `@derive(order)` on `a` or `impl order for a` .
Related
Attributes
Attributes are @name notes before an item: the ones the compiler acts on today (derive, checkfree, inline_always, leaf) and the library's (json), and what happens to an unknown one.
@checkfree
@checkfree: a promise that the optimised function has no index tests left, and how to write a loop the compiler can prove.