advRefl.go
的Go代码进行演示。package mainimport ( "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()1for i := 0; i < r1.NumField(); i++ {2if r1.Field(i).Interface() != r2.Field(i).Interface() {3return false4}5}6return trueCopied!} ```
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)1for j := 0; j < r.NumMethod(); j++ {2m := r.Method(j).Type()3fmt.Println(t.Method(j).Name, "-->", m)4}Copied!} ```
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))1var p struct{}2r := reflect.New(reflect.ValueOf(&p).Type()).Elem()3fmt.Printf("The type of r is %s\n", reflect.TypeOf(r))Copied!```
a1 := a{1, 2.1, "A1"} a2 := a{1, -2, "A2"}1if a1.compareStruct(a1) {2fmt.Println("Equal!")3}45if !a1.compareStruct(a2) {6fmt.Println("Not Equal!")7}89var f *os.File10printMethods(f)Copied!} ```
a1.compareStruct(a1)
调用返回true
,因为我们正在比较a1
与自身,而a1.compareStruct(a2)
调用将返回false
,因为a1
和a2
变量的值不同。advRefl.go
将得到以下输出:1$ go run advRefl.go2The type of x1 is main.t13The type of x2 is main.t24The type of r is reflect.Value5Equal!6Not Equal!7Type to examine: *os.File8Chdir --> func() error9Chmod --> func(os.FileMode) error10Chown --> func(int, int) error11Close --> func() error12Fd --> func() uintptr13Name --> func() string14Read --> func([]uint8) (int, error)15ReadAt --> func([]uint8, int64) (int, error)16Readdir --> func(int) ([]os.FileInfo, error)17Readdirnames --> func(int) ([]string, error)18Seek --> func(int64, int) (int64, error)19Stat --> func() (os.FileInfo, error)20Sync --> func() error21Truncate --> func(int64) error22Write --> func([]uint8) (int, error)23WriteAt --> func([]uint8, int64) (int, error)24WriteString --> func(string) (int, error)Copied!
reflect.New()
返回的r
变量的类型是reflect.Value
。另外,printMethods()
方法的输出可以看到*os.File
类型支持很多的方法,例如:Chdir()
、Chmod()
等。