代码生成
Experimental Feature
Code generation is an experimental feature in Fory Go. The API and behavior may change in future releases. The reflection-based path remains the stable, recommended approach for most use cases.
Fory Go 为性能关键路径提供可选的 AOT 代码生成,可消除反射开销并提升编译期类型安全。
为什么使用代码生成?
| Aspect | Reflection-Based | Code Generation |
|---|---|---|
| Setup | Zero configuration | Requires go generate |
| Performance | Good | Better (no reflection) |
| Type Safety | Runtime | Compile-time |
| Maintenance | Automatic | Requires regeneration |
Use code generation when:
- Maximum performance is required
- Compile-time type safety is important
- Hot paths are performance-critical
Use reflection when:
- Simple setup is preferred
- Types change frequently
- Dynamic typing is needed
- Code generation complexity is undesirable
安装
Install the fory generator binary:
go install github.com/apache/fory/go/fory/cmd/fory@latest
GO111MODULE=on go get -u github.com/apache/fory/go/fory/cmd/fory
Ensure $GOBIN or $GOPATH/bin is in your PATH.
基本用法
Step 1: Annotate Structs
Add the //fory:generate comment above structs:
package models
//fory:generate
type User struct {
ID int64 `json:"id"`
Name string `json:"name"`
}
//fory:generate
type Order struct {
ID int64
Customer string
Total float64
}
Step 2: Add Go Generate Directive
Add a go:generate directive (once per file or package):
//go:generate fory -file models.go
Or for the entire package:
//go:generate fory -pkg .
Step 3: Run Code Generation
go generate ./...
This creates models_fory_gen.go with generated serializers.