在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
go 反射反射:可以在运行时动态获取变量的相关信息 import (“reflect”)
package main import ( "fmt" "reflect" ) type Student struct { Name string Age int Score float32 } func test(b interface{}) { t := reflect.TypeOf(b) fmt.Println(t) v := reflect.ValueOf(b) k := v.Kind() fmt.Println(k) iv := v.Interface() stu, ok := iv.(Student) if ok { fmt.Printf("%v %T\n", stu, stu) } } func testInt(b interface{}) { val := reflect.ValueOf(b) val.Elem().SetInt(100) c := val.Elem().Int() fmt.Printf("get value interface{} %d\n", c) fmt.Printf("string val:%d\n", val.Elem().Int()) } func main() { var a Student = Student{ Name: "stu01", Age: 18, Score: 92, } test(a) var b int = 1 b = 200 testInt(&b) fmt.Println(b) }
获取变量的值
改变变量的值
用反射操作结构体
package main import ( "fmt" "reflect" ) type NotknownType struct { s1 string s2 string s3 string } func (n NotknownType) String() string { return n.s1 + "-" + n.s2 + "-" + n.s3 } var secret interface{} = NotknownType{"Ada", "Go", "Oberon"} func main() { value := reflect.ValueOf(secret) // <main.NotknownType Value> typ := reflect.TypeOf(secret) // main.NotknownType fmt.Println(typ) knd := value.Kind() // struct fmt.Println(knd) for i := 0; i < value.NumField(); i++ { fmt.Printf("Field %d: %v\n", i, value.Field(i)) //value.Field(i).SetString("C#") } results := value.Method(0).Call(nil) fmt.Println(results) // [Ada - Go - Oberon] }
|
请发表评论