Parco and Go 1.27 Generic Methods
Go 1.27 lets a method declare its own type parameters. I had been waiting for that since I wrote Parco, because the builder API was shaped around its absence. This post shows what the builder looked like under the old constraint, what it looks like with the constraint gone, what the change cost at runtime (no measurable difference), and the two things the new shape made easy: a typed registry and a code generator. All of it shipped today as v0.14.0.
The constraint
A Parco model is a list of fields. Each field is a wire type, a getter
and a setter. The builder is generic over the struct, Builder[T], and
each field method knows its own wire type:
parser, compiler := parco.Builder[Example](factory).
SmallVarchar(
func(e *Example) string { return e.Greet },
func(e *Example, s string) { e.Greet = s },
).
UInt8(
func(e *Example) uint8 { return e.Age },
func(e *Example, n uint8) { e.Age = n },
).
Parco()
That works for primitives because uint8 is spelled out in the method
name. It stops working the moment a field has an element type of its
own. A slice of strings needs T and string; a map needs T, the key
type and the value type. Before 1.27 a method could only use the type
parameters of its receiver, so Slice could not say “and U is whatever
you give me”. The workaround was to move the field construction out to a
free function, which can be generic over anything, and have the method
accept the result:
Slice(
parco.SliceField[Example, string](
parco.UInt8Header(),
parco.SmallVarchar(),
func(e *Example, f parco.SliceView[string]) { e.Friends = f },
func(e *Example) parco.SliceView[string] { return e.Friends },
),
).
Struct(
parco.StructField[Example, Animal](
func(e *Example) Animal { return e.Pet },
func(e *Example, a Animal) { e.Pet = a },
animalBuilder,
),
).
The user types Example on every nested field, inside a call that only
exists to carry U into a method that cannot declare it. On the library
side the same workaround repeats for slices, arrays, maps, optionals and
structs: a struct per field kind, three constructors each, and three
one-line methods on the builder, the parser and the compiler. Nineteen
primitive methods on each of three builders, plus the field constructor
families, is most of the public surface, and all of it is there to route
a type parameter.
With generic methods
The release notes put it in one sentence: a
method declaration may declare its own type parameters. T can come from
the receiver and U from the method, which is the thing the builder
needed:
func (m *Model[T]) Field[U any](typ Type[U], getter Getter[T, U], setter Setter[T, U]) *Model[T]
Parco already had a Type[U] interface, with Parse and Compile, and
it already had combinators that build one from others: Slice(header, inner), MapType(header, key, value), Option(inner). The field
methods had nothing to do with the wire format; they only carried U. So
one generic Field replaces all of them, and the combinators are
passed in directly. U is inferred from the Type[U] argument, or
from the getter, so nothing is written twice:
example := parco.NewModel[Example](factory).
Field(parco.SmallVarchar(),
func(e *Example) string { return e.Greet },
func(e *Example, v string) { e.Greet = v }).
Field(parco.Slice(parco.UInt8Header(), parco.SmallVarchar()),
func(e *Example) parco.Iterable[string] { return parco.SliceView[string](e.Friends) },
func(e *Example, v parco.Iterable[string]) { e.Friends = v.Unwrap() }).
Field(animal,
func(e *Example) Animal { return e.Pet },
func(e *Example, v Animal) { e.Pet = v })
The nested struct is the last field. animal is another Model, and a
Model[T] implements Type[T], so it goes through the same Field
call as a uint8 does. StructField, SliceField and the hand-written
[Example, string] are no longer needed.
Inside the library a single unexported struct holds the type, the getter and the setter of a field:
type typedField[T, U any] struct {
typ Type[U]
getter Getter[T, U]
setter Setter[T, U]
}
func (f typedField[T, U]) parse(item *T, r io.Reader) error {
value, err := f.typ.Parse(r)
if err != nil {
return err
}
f.setter(item, value)
return nil
}
func (f typedField[T, U]) compile(item *T, w io.Writer) error {
return f.typ.Compile(f.getter(item), w)
}
What it cost at runtime
The hot path is unchanged:
one interface call per field, the same Type[U] doing the same reads and
writes. The generic method only changes how the model is assembled, which
happens once.
The existing compile benchmark runs the old Compiler over a struct with
two strings, a uint16, a slice, a map, a bool and two floats, at three
payload sizes. I added the same model built with Model.Field and ran
both ten times on go1.27.2:
old (Compiler) new (Model) delta
small (91 B) 450.4 ns 447.5 ns -0.6% (p=0.007)
medium (742 B) 2.546 us 2.548 us noise (p=0.468)
large (8.1 KB) 25.23 us 25.24 us noise (p=0.739)
In every row, old and new report the same payload size, bytes per op and allocations per op: 184 B and 3 allocs, whatever the payload, because the writer is pooled. The benchmark and the test that produced these numbers are in the repository next to the old ones, so the pair can be rerun.
Keeping the Go 1.22 minimum
Parco’s minimum is Go 1.22 and I did not want a syntax feature to move
it. A per-file build constraint turns out to be enough. The file that
defines Model starts with //go:build go1.27, and that line does two
things: it excludes the file on older toolchains, and it raises the
language version for that file alone, so the generic method compiles
even though go.mod still says 1.22. I checked both directions in a
throwaway module. With the constraint the file builds; without it the
compiler says generic method requires go1.27 or later (-lang was set to go1.22; check go.mod).
So the old Builder stays, unchanged, for everyone, and Model exists
for anyone on 1.27. Both produce the same bytes.
A registry that is a type
Parco has had a multi-model builder for a while: register several models
under an id, write the id as a header, and dispatch on it when parsing.
I didn’t like its shape. It took models as any, checked them at
runtime, and it could not be used as a field of another model because it
was not a Type.
With Model in place the registry is a few lines. It is a map from id to
model, and it implements Type[Entry[ID]], where Entry is the id plus
the value:
registry := parco.NewRegistry[uint8](parco.UInt8()).
Register(1, animal).
Register(2, flat)
err := registry.Compile(parco.Entry[uint8]{ID: 1, Value: Animal{Specie: "cat"}}, &buf)
entry, err := registry.Parse(&buf) // entry.ID == 1, entry.Value.(Animal)
Register is a generic method too, Register[U](id ID, m *Model[U]),
so passing something that is not a model is a compile error. And because
the registry is a Type, an envelope with a sequence number and a
variable payload is an ordinary model with two fields, one of which is
the registry. The old multi-model builder stays for the old API.
A generator for the getters and setters
Every example above has the same two closures per field, and with struct
tags those two closures would not exist. easyjson solved it for
JSON by parsing the package and writing the marshal code. Parco now does
the same with parco-gen: it reads the structs, picks the ones with at
least one parco tag, and writes the Model call for each, closures
included.
//go:generate go run github.com/sonirico/parco/cmd/parco-gen
type Example struct {
Greet string `parco:"hdr=uint8"`
Num uint16 `parco:"be"`
Friends []string
Pet Pet
Pointer *int
Cache string `parco:"-"`
}
The wire type comes from the Go type. uint16 is little-endian unless
the tag says be; string is a varchar with a uint16 header unless the
tag picks another; []T is a slice, [N]T an array, map[K]V a map,
*T an optional, time.Time a UTC timestamp, and a struct declared in
the same package is its own generated model. Fields go on the wire in
declaration order, and - leaves one out.
The generator is stdlib only, go/parser and go/ast in and
go/format out, and it writes the same Field calls as the hand-written
model above, wrapped in a NewXxxModel function per struct. Its test
regenerates the example package in the repository and
compares the result with the committed file, so the generator and the
documented output cannot drift apart without a failing test. The generated
file carries the same //go:build go1.27 line as Model, which is why
the generator only targets the new API.
Two things I had to touch
The optional type did not implement ByteLength, so it was never a
Type[U], and it had its own field struct for that reason. Adding the
method was four lines and it made Option(...) a valid argument to
Field. The slice and array types expose Iterable[U] rather than
SliceView[U], so the getter returns an interface and the setter calls
Unwrap(). That is one line of noise per slice field and it is the
next thing to clean up.
Compatibility and the old API
The release is additive: v0.14.0 adds Model, Registry and
parco-gen and removes nothing. Writing a parser or a compiler by hand
with Builder keeps working, on Go 1.22 and up, and I intend to keep it
that way. Most of the primitive methods and field families exist to route
a type parameter, which is why I’m asking whether they should go once
1.27 is the oldest supported toolchain. Whatever the answer, it will land
in a 0.x release; there is no 1.0 planned. Performance is not a reason to
decide either way: the benchmark shows no difference.