Custom Derive
@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 Zolo source, spliced next
// to the type. The source can be `impl Trait for Self` OR — when you just want
// to add a method without declaring a trait — an INHERENT `impl Self { ... }`.
@derive_for(FieldList)
fn derive_field_list(info) -> str {
var names = "\"\""
var first = true
for f in info.fields {
if first == false { names = names + " + \",\"" }
names = names + " + \"" + f.name + "\""
first = false
}
// Inherent impl: adds `field_list` directly onto the type — no `trait`
// declaration needed, and it coexists with any hand-written `impl` blocks.
return "impl " + info.name + " \{ 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