GoGo语言实践

Golang reflect 反射 struct 动态获取tim

2020-02-25  本文已影响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
        }
    }
}

=== 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

上一篇 下一篇

猜你喜欢

热点阅读