reflect: add FuncOf function

This also involves adding functions to typelinks along with a minor
change to ensure they are sorted correctly.

Change-Id: I054a79b6498a634cbccce17579f52c299733c2cf
Reviewed-on: https://go-review.googlesource.com/1996
Reviewed-by: Ian Lance Taylor <iant@golang.org>
This commit is contained in:
Dave Day 2014-12-23 15:19:30 +11:00
parent f5b5e41814
commit e1c1fa2919
4 changed files with 199 additions and 5 deletions

View file

@ -3663,6 +3663,67 @@ func TestMapOfGCValues(t *testing.T) {
}
}
func TestTypelinksSorted(t *testing.T) {
var last string
for i, n := range TypeLinks() {
if n < last {
t.Errorf("typelinks not sorted: %q [%d] > %q [%d]", last, i-1, n, i)
}
last = n
}
}
func TestFuncOf(t *testing.T) {
// check construction and use of type not in binary
type K string
type V float64
fn := func(args []Value) []Value {
if len(args) != 1 {
t.Errorf("args == %v, want exactly one arg", args)
} else if args[0].Type() != TypeOf(K("")) {
t.Errorf("args[0] is type %v, want %v", args[0].Type, TypeOf(K("")))
} else if args[0].String() != "gopher" {
t.Errorf("args[0] = %q, want %q", args[0].String(), "gopher")
}
return []Value{ValueOf(V(3.14))}
}
v := MakeFunc(FuncOf([]Type{TypeOf(K(""))}, []Type{TypeOf(V(0))}, false), fn)
outs := v.Call([]Value{ValueOf(K("gopher"))})
if len(outs) != 1 {
t.Fatalf("v.Call returned %v, want exactly one result", outs)
} else if outs[0].Type() != TypeOf(V(0)) {
t.Fatalf("c.Call[0] is type %v, want %v", outs[0].Type, TypeOf(V(0)))
}
f := outs[0].Float()
if f != 3.14 {
t.Errorf("constructed func returned %f, want %f", f, 3.14)
}
// check that types already in binary are found
type T1 int
testCases := []struct {
in, out []Type
variadic bool
want interface{}
}{
{in: []Type{TypeOf(T1(0))}, want: (func(T1))(nil)},
{in: []Type{TypeOf(int(0))}, want: (func(int))(nil)},
{in: []Type{SliceOf(TypeOf(int(0)))}, variadic: true, want: (func(...int))(nil)},
{in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false)}, want: (func(int) bool)(nil)},
{in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false), TypeOf("")}, want: (func(int) (bool, string))(nil)},
}
for _, tt := range testCases {
checkSameType(t, Zero(FuncOf(tt.in, tt.out, tt.variadic)).Interface(), tt.want)
}
// check that variadic requires last element be a slice.
FuncOf([]Type{TypeOf(1), TypeOf(""), SliceOf(TypeOf(false))}, nil, true)
shouldPanic(func() { FuncOf([]Type{TypeOf(0), TypeOf(""), TypeOf(false)}, nil, true) })
shouldPanic(func() { FuncOf(nil, nil, true) })
}
type B1 struct {
X int
Y int