Go reflect反射

Posted vincenshen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Go reflect反射相关的知识,希望对你有一定的参考价值。

 

package main

import (
    "reflect"
    "fmt"
)

type User struct {
    Name string `json:"name"`
    Age int
    Sex string
}

func TestType(a interface{}) {
    typeOf := reflect.TypeOf(a)
    fmt.Printf("typeof = %v
", typeOf)
    kind := typeOf.Kind()
    switch kind {
    case reflect.Int:
        fmt.Println("a is an int")
    case reflect.String:
        fmt.Println("a is a string")
    }
}

func TestValue(a interface{}) {
    valueOf := reflect.ValueOf(a)
    switch valueOf.Kind() {
    case reflect.Ptr:
        i := valueOf.Elem().Type()
        switch i.Kind() {
        case reflect.Int:
            valueOf.Elem().SetInt(10000)
        case reflect.String:
            valueOf.Elem().SetString("hello world")
        }
    }
}

func Marshal(a interface{}) {
    valueOf := reflect.ValueOf(a)
    typeOf := valueOf.Type()
    jsonStr := ""
    switch typeOf.Kind() {
    case reflect.Struct:
        numField := typeOf.NumField()
        for i:=0; i<numField; i++ {
            structField := typeOf.Field(i)
            valueField := valueOf.Field(i)
            name := structField.Name
            if structField.Tag.Get("json") != "" {
                name = structField.Tag.Get("json")
            }
            if valueField.Type().Kind() == reflect.String {
                jsonStr += fmt.Sprintf("  "%s": "%v"", name, valueField.Interface())
            } else {
                jsonStr += fmt.Sprintf("  "%s": %v", name, valueField.Interface())

            }
            if numField - i > 1 {
                jsonStr += ",
"
            }
        }
        jsonStr = "{
" + jsonStr + "
}"
    }
    fmt.Printf("%s", jsonStr)
}

func main() {
    var a int
    TestType(a)

    var b string
    TestType(b)

    TestValue(&a)
    TestValue(&b)

    fmt.Println(a, b)

    var user User
    user.Name = "alex"
    user.Age = 100
    user.Sex = "man"
    Marshal(user)
}

 

以上是关于Go reflect反射的主要内容,如果未能解决你的问题,请参考以下文章

Go反射编程

go语言的reflect(反射)

[Go关于反射] reflect包

[Go关于反射] reflect包

[Go关于反射] reflect包

GO开发[六]:golang反射(reflect)