package main import ( "fmt" "go/types" ) func main() { // Define a function type with two parameters params := []*types.Var{ types.NewVar(0, nil, "a", types.Typ[types.Int]), types.NewVar(0, nil, "b", types.Typ[types.Int]), } result := []*types.Var{types.NewVar(0, nil, "", types.Typ[types.Int])} fnType := types.NewSignature(nil, types.NewTuple(params...), types.NewTuple(result...), false) // Create a new instance of the function type and call it fn := types.NewFunc(0, nil, "add", fnType) args := []types.Type{types.Typ[types.Int], types.Typ[types.Int]} ret := fnType.Results() values := []types.Value{types.NewConst(0, types.Typ[types.Int], 2), types.NewConst(0, types.Typ[types.Int], 3)} resultValues := values[:len(ret)] results := types.NewTuple(resultValues...) res, _ := types.DefaultTypeSet().AssertableTo(results, ret) intRes := res.(types.Type) result := fmt.Sprintf("%v", intRes) fmt.Println(result) }
import ( "go/types" "reflect" ) // Test function func foo(x int, y string) float32 { return float32(x) + y } func main() { fn := reflect.ValueOf(foo) ft := fn.Type() // Use Func to get the signature of the function sig := types.NewSignature(nil, nil, nil, false) types.FuncOf(types.Typ[types.Int], types.NewTuple(types.NewVar(0, nil, "", types.Typ[types.String])), false) fmt.Println(sig) }In this example, we use the reflect package to get a reflection of the `foo` function, and then use Func to get its signature. The resulting signature is used to verify that the function has the expected type.