直接上代码
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
有疑问加站长微信联系(非本文作者)