1. 程式人生 > >go語言---reflect

go語言---reflect

interface face lock func ace clas main port blog

go語言---reflect

https://blog.csdn.net/cyk2396/article/details/78902953

一.reflect的使用:

import (
    "fmt"
    "reflect"
)
 
type Student struct {
    Name string
    Age  int
}
 
func main() {
    var x int = 1
    student := Student{Name: "zs", Age: 26}
 
    //1.reflect.TypeOf() 返回值Type類型
    fmt.Println("x type: ", reflect.TypeOf(x))
    fmt.Println("student type: ", reflect.TypeOf(student))
 
    //2.reflect.ValueOf() 返回值Value類型
    fmt.Println("x value: ", reflect.ValueOf(x))
    fmt.Println("student value: ", reflect.ValueOf(student))
 
    //3.value.Kind() 返回值Kind類型 註意與Type的不同
    fmt.Println("x kind: ", reflect.ValueOf(x).Kind())
    fmt.Println("student kind: ", reflect.ValueOf(student).Kind())
 
    //4.修改反射對象,修改反射對象的前提條件是其值是可設置的
    var a int = 10
    v := reflect.ValueOf(&a)
    e := v.Elem()
    e.SetInt(15)
    fmt.Println(e.CanSet()) //根據CanSet()返回值可確定是否可以設置
    fmt.Println(a)          // 根據結果我們可知 a=15
 
    //5.遍歷結構體字段內容
    s := reflect.ValueOf(&student).Elem()
    studentType := s.Type()
    for i := 0; i < s.NumField(); i++ {
        f := s.Field(i)
        fmt.Printf("%d %s %s = %v\n", i, studentType.Field(i).Name, f.Type(), f.Interface())
    }
}

輸出結果:

x type: int
student type: main.Student
x value: 1
student value: {zs 26}
x kind: int
student kind: struct
true
15
0 Name string = zs
1 Age int = 26

go語言---reflect