-
Notifications
You must be signed in to change notification settings - Fork 5
Generic Function
For generic function provider
package compare
import "github.com/v2pro/wombat/generic"
var SimpleValue = generic.
Func("compareSimpleValue(val1 T, val2 T) int").
Params("T", "the type of value to compare").
Source(`
if val1 < val2 {
return -1
} else if val1 == val2 {
return 0
} else {
return 1
}
')For generic function users, you will need to expand generic function to several normal functions by different template arguments.
import "github.com/v2pro/wombat/generic"
func init() {
generic.Declare(compare.SimpleValue, "T", generic.Float32)
}
func MyFunction() {
compareSimpleValue := generic.Expand(compare.SimpleValue, "T", generic.Float32).
(func(float32, float32) int)
compareSimpleValue(2.5, 3.6)
}If dynamic compilation is acceptable (running go build in production environment), you can use generic.Expand without generic.Declare first.
generic.Expand relies on code generation. There are 2 options you can choose:
- Dynamic compilation: generate the code, use
go buildto build plugin and load the plugin in runtime. - Static codegen: generate the code and include the generated code in your other code.
go toolchain need to be installed in the production environment. Referenced packages need to be available at $GOPATH.
generic.Declare is optional in this mode.
Every generic.Expand must have corresponding generic.Declare in the init() function. We use the info declared to generate the code. The code by default is generated into your package as a single generated.go file.
gen code your_pkgBecause it is in your package, there is no need to add additional code to include the generated code. generated.go will register expanded functions into global variable, so that generic.Expand can look it up.