列举几个反射的例子:1)简单类型反射,2)复杂类型反射,3)对反射回来的数据的可修改属性
1、简单类型反射
1.1)代码
package main import ( "fmt" "reflect" ) func main() { var x float64 = 3.4 v := reflect.ValueOf(x) fmt.Println("type :", v.Type()) fmt.Println("kind is float64:", v.Kind() == reflect.Float64) fmt.Println("value:", v.Float()) }
1.2)运行结果
$ go run reflect.go type : float64 kind is float64: true value: 3.4
2、复杂类型反射
2.1)代码
1 package main 2 3 import ( 4 "fmt" 5 "reflect" 6 ) 7 8 type T struct { 9 A int 10 B string 11 } 12 13 func main () { 14 t := T{203, "mh203"} 15 s := reflect.ValueOf(&t).Elem() 16 typeOfT := s.Type() 17 for i := 0; i < s.NumField(); i++ { 18 f := s.Field(i) 19 fmt.Printf("%d: %s %s = %v\n", i, 20 typeOfT.Field(i).Name, f.Type(), f.Interface()) 21 } 22 }
2.2)运行结果
$ go run structreflect.go 0: A int = 203 1: B string = mh203
3、通过反射获得的变量的可设置属性
3.1)代码实例
1 package main 2 3 import ( 4 "fmt" 5 "reflect" 6 ) 7 8 func testA() { 9 var x float64 = 3.4 10 v := reflect.ValueOf(x) 11 if(true == v.CanSet()) { 12 fmt.Println("v is setable") 13 //v.Set(4.1) 14 } else { 15 fmt.Println("v is not setable") 16 } 17 } 18 19 func testB() { 20 var x float64 = 3.4 21 p := reflect.ValueOf(&x) 22 fmt.Println("type of p:", p.Type()) 23 fmt.Println("settablitty of p :", p.CanSet()) 24 25 v := p.Elem() 26 fmt.Println("settablitty of v:", v.CanSet()) 27 28 v.SetFloat(7.1) 29 fmt.Println(v.Interface()) 30 fmt.Println(x) 31 } 32 33 func main() { 34 testA() 35 testB() 36 }
3.2)运行结果
$ go run set.go v is not setable type of p: *float64 settablitty of p : false settablitty of v: true 7.1 7.1
时间: 2024-10-13 22:21:44