07.5.2 反射进阶
在本节中,我们将探讨反射的更高级的用法,将使用相对较小的advRefl.go的Go代码进行演示。
>package main
import ( "fmt" "os" "reflect" )
type t1 int type t2 int ```
可以注意到尽管t1和t2类型都基于int类型,因此本质上也与int类型相同,但Go语言将它们视为完全不同的类型。它们在Go编译器解析后的内部表示分别是main.t1和main.t2。
>type a struct { X int Y float64 Text string }
func (a1 a) compareStruct(a2 a) bool { r1 := reflect.ValueOf(&a1).Elem() r2 := reflect.ValueOf(&a2).Elem()
for i := 0; i < r1.NumField(); i++ { if r1.Field(i).Interface() != r2.Field(i).Interface() { return false } } return true} ```
在这个代码段中,我们定义了一个名为a的Go结构类型,并实现了一个名为compareStruct()的Go函数。这个函数的目的是找出类型a的两个变量是否完全相同。如您所见,compareStruct()使用reflection.go中的Go代码来执行其任务。
>func printMethods(i interface{}) { r := reflect.ValueOf(i) t := r.Type() fmt.Printf("Type to examine: %s\n", t)
for j := 0; j < r.NumMethod(); j++ { m := r.Method(j).Type() fmt.Println(t.Method(j).Name, "-->", m) }} ```
func main() { x1 := t1(100) x2 := t2(100) fmt.Printf("The type of x1 is %s\n", reflect.TypeOf(x1)) fmt.Printf("The type of x2 is %s\n", reflect.TypeOf(x2))
```
a1 := a{1, 2.1, "A1"} a2 := a{1, -2, "A2"}
} ```
正如您稍后将看到的,a1.compareStruct(a1)调用返回true,因为我们正在比较a1与自身,而a1.compareStruct(a2)调用将返回false,因为a1和a2变量的值不同。
执行advRefl.go将得到以下输出:
可以看到由reflect.New()返回的r变量的类型是reflect.Value。另外,printMethods()方法的输出可以看到*os.File类型支持很多的方法,例如:Chdir()、Chmod()等。
Last updated
Was this helpful?