Type-driven code generation for Go
gen is an attempt to bring some generics-like functionality to Go. It uses type annotations to add “of T” functionality to your packages.
gen generates code for your types, at development time, using the command line. It is not an import; the generated source becomes part of your package and takes no external dependencies.
Of course, start by installing Go, setting up paths, etc. Then:
Create a new Go project, and
Now, mark it up with a
And at the command line, simply type:
You should see a new file, named
The annotation syntax will look familiar to Go users, it is modeled after struct tags.
The annotation is a comment that begins with the
The tags & values are interpreted by TypeWriters.
gen is driven by “type writers” – packages which are responsible for interpreting the annotated tags and turning them into generated code. Learn more…
The goal of gen is not just to offer conveniences, but stronger typing. By generating strongly-typed methods and containers, we avoid having to use
We gain compile-time safety and (perhaps) performance.
Yes! It felt a bit dirty to us at the beginning, too. But it turns out that a lot of actual generics implementations look a lot like code generation – you just don’t see it. (Compilers and JITs do it for you.)
Code generation removes mystery. It’s just code, right there in your package. Read it. The history goes in your repo like everything else.
You get all the usual compiler checks and optimizations, of course, so gen won’t introduce surprises in production.
gen is a tool that helps the developer produce code on their local workstation, alongside their text editor and utilities.
Is there a video?
Wait, is this
No, that’s different (and very cool).
The two tools are complementary.
Can I run gen on the server?
Like as part of the build? Sure, but that’s not what it’s designed around so we don’t recommend it.
It’s a local dev tool, not a platform or (shudder) a framework. Run it locally, test it, and commit the generated code to the repo.
What if my code is incorrect?
gen parses and type-checks your source code. Having correct, buildable source code before you begin is important.
That said, there are classes of errors that gen can optionally tolerate, via the