Derived code

#[derive(...)] before a struct or an enum writes methods for it, from its fields or members:

import "std/json"

#[derive(Equal, Hash, ToText, Clone, Default, Json)]
struct User do
    #[json(name: "userId")]
    int id
    str name
    str[] tags = []
    #[json(skip_if_null)]
    str nickname = null
end
Derive Writes So that
Equal func equals(self, T other) bool, comparing each field == compares values; arrays, maps, and options item by item
Hash func hash(self) i64, from each field's hash the type can be a map key
Clone func clone(self) T, cloning each field clone(value) is a deep copy
ToText func to_text(self) str, as User(id: 7, name: "Ana", ...) print and to_str show it
Default func default() T, with each field's default, or zero, "", false, an empty array or map, NONE, null for a struct, and E.default() for an enum User.default()
Json func to_json(self) Json and func from_json(Json value) Result[T] it converts to and from std/json values

For an enum, the members are compared, hashed, cloned, and shown with their values. In JSON a plain enum is its member's name, and a member with values an object with the member's name under "kind" and each value under its own name. derive(Json) needs import "std/json", and the types of the fields need their own to_json and from_json, as derived ones are; it is for types without type parameters.

from_json reports a missing field, or a value of the wrong kind, as an error that names the field. A field with a default, a field that can be null, and an Option may be missing: it keeps its default, null, or NONE. A field's #[json(name: "key")] gives the key it has in JSON, and #[json(skip_if_null)] leaves out a field that is null instead of writing null.

The derived methods are ordinary methods, which cuarzo c shows with the others; a type that has a method of the same name cannot derive it. An error in derived code points at the derive that wrote it.

Hashing and copying

hash(x) is an i64 that is equal for equal values: numbers, characters, strings, and plain enums hash by value, arrays by their items, and other types with their hash method. A type with hash and equals methods, written or derived, can be a map key. clone(x) is a deep copy: arrays and maps are copied with their items, and other types with their clone method; values that cannot change, such as numbers, strings, tuples, and enum members, are shared, and a struct without clone cannot be cloned.