Skip to content

Generic Function

Tao Wen edited this page Jul 21, 2017 · 16 revisions

Write

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
    }
')

Use

For generic function users, you will need to expand generic function to several normal functions by different template arguments.

Declare & Expand

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.

Code generation options

generic.Expand relies on code generation. There are 2 options you can choose:

  • Dynamic compilation: generate the code, use go build to build plugin and load the plugin in runtime.
  • Static codegen: generate the code and include the generated code in your other code.

Dynamic compilation

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.

Static Codegen

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_pkg

Because 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.

Clone this wiki locally