ZhangZhihui's Blog  

Reflection can be used to inspect the type of variables and to dynamically access and modify their values. Following is a simple example of using reflection to inspect a variable's type:

 

func main() {
    v1 := 42
    inspectVariable(v1)

    v2 := map[int]string{1: "aaa"}
    inspectVariable(v2)
}

func inspectVariable(variable interface{}) {
    t := reflect.TypeOf(variable)
    v := reflect.ValueOf(variable)
    fmt.Println("Type:", t)
    fmt.Println("Value:", v)
}

 

zzh@ZZHPC:/zdata/Github/ztest$ go run main.go
Type: int
Value: 42
Type: map[int]string
Value: map[1:aaa]

 

posted on 2024-04-02 22:10  ZhangZhihuiAAA  阅读(10)  评论(0)    收藏  举报