美文网首页GoGo语言实践
Golang reflect 反射 struct 动态获取tim

Golang reflect 反射 struct 动态获取tim

作者: 承诺一时的华丽 | 来源:发表于2020-02-25 15:53 被阅读0次

    直接上代码

    package main
    
    import (
        "fmt"
        "reflect"
        "testing"
        "time"
    )
    
    type Stu struct {
        Str  string
        Time time.Time
    }
    
    func TestTime(t *testing.T) {
        stu := Stu{Str: "test", Time: time.Now()}
        print(stu)
    }
    
    func print(t interface{})  {
        getType := reflect.TypeOf(t)
        getValue := reflect.ValueOf(t)
        for i := 0; i < getType.NumField(); i++ {
            field := getType.Field(i)
            switch field.Type.String() {
            case "time.Time":
                fmt.Printf("%s: %v = %v\n", field.Name, field.Type, getValue.Field(1).Interface().(time.Time))
                break
            default:
                value := getValue.Field(i)
                fmt.Printf("%s: %v = %v\n", field.Name, field.Type, value.String())
                break
            }
        }
    }
    
    
    • test结果
    === RUN   TestTime
    Str: string = test
    Time: time.Time = 2020-02-25 15:51:28.1895942 +0800 CST m=+0.009973701
    --- PASS: TestTime (0.02s)
    PASS
    
    Process finished with exit code 0
    
    

    相关文章

      网友评论

        本文标题:Golang reflect 反射 struct 动态获取tim

        本文链接:https://www.haomeiwen.com/subject/uqbtchtx.html