我正在研究用Go编写的模板系统,这意味着它需要自由使用reflect包.在这种特定情况下,我需要能够动态调用方法interface{}.奇怪的是,只要我的数据是已知类型,我的反射逻辑就可以正常工作,但如果数据属于类型则不行interface{}.
在下面的例子中,您可以看到逻辑中main()和Pass()相同.唯一的区别是数据是已知类型还是已知类型interface{}
去玩:http://play.golang.org/p/FTP3wgc0sZ
package main
import (
"fmt"
"reflect"
)
type Test struct {
Start string
}
func (t *Test) Finish() string {
return t.Start + "finish"
}
func Pass(i interface{}) {
_, ok := reflect.TypeOf(&i).MethodByName("Finish")
if ok {
fmt.Println(reflect.ValueOf(&i).MethodByName("Finish").Call([]reflect.Value{})[0])
} else {
fmt.Println("Pass() fail")
}
}
func main() {
i := Test{Start: "start"}
Pass(i)
_, ok := reflect.TypeOf(&i).MethodByName("Finish")
if ok {
fmt.Println(reflect.ValueOf(&i).MethodByName("Finish").Call([]reflect.Value{})[0])
} else { …Run Code Online (Sandbox Code Playgroud) 该程序的输出是map[],但我想要map[Id:true name:true]
我正在尝试干燥一些 SQL CRUD 代码,并认为嵌入一个处理数据库读写的持久性结构会很好。在下面的示例中,持久性结构将是内部,我的模型将是外部。谢谢!
http://play.golang.org/p/fsPqJ-6aLI
package main
import (
"fmt"
"reflect"
)
type Inner struct {
}
type Outer struct {
Inner
Id int
name string
}
func (i *Inner) Fields() map[string]bool {
typ := reflect.TypeOf(*i)
attrs := make(map[string]bool)
if typ.Kind() != reflect.Struct {
fmt.Printf("%v type can't have attributes inspected\n", typ.Kind())
return attrs
}
// loop through the struct's fields and set the map
for i := 0; i < typ.NumField(); i++ {
p := …Run Code Online (Sandbox Code Playgroud)