16 · Reflection & Metaprogramming
Custom Derive
Register your own derive with @derive_for: a comptime fn receives typeinfo and returns Zolo source to splice.
On this page
@derive_for(Trait) registers a comptime function as the code generator for
that trait. The function receives typeinfo(Self) and returns a Zolo source
string — either an impl Trait for Self or an inherent impl Self { ... } —
which the compiler splices next to the type definition. No compiler modification
required.
Register a FieldList derive with @derive_for, generate an inherent impl that joins field names as a comma-separated string, and verify a.field_list() returns "id,owner,balance".
12-derive-custom.zolo
// Feature: define your OWN derive. `@derive_for(Trait)` registers a comptime
// function that receives typeinfo(Self) and returns structured Zolo syntax,
// spliced next to the type. The result can be `impl Trait for Self` OR — when
// you just want a method — an INHERENT `impl Self { ... }`.
@derive_for(FieldList)
fn derive_field_list(info) -> Syntax<.Items> {
let names = info.fields.map(|field| field.name).join(",")
// Inherent impl: adds `field_list` directly onto the type — no `trait`
// declaration needed, and it coexists with any hand-written `impl` blocks.
return quote items {
impl ${info.ref} {
fn field_list(self) -> str { return ${names} }
}
}
}
@derive(FieldList)
struct Account {
id: int,
owner: str,
balance: int,
}
let a = Account.new(id: 1, owner: "x", balance: 0)
print(a.field_list())
// expected: id,owner,balance