In my test I have a function that can get a value from a struct like this:
func getField(v interface{}, field string) string {
r := reflect.ValueOf(v)
f := reflect.Indirect(r).FieldByName(field)
t := f.Kind()
switch t {
case reflect.Int, reflect.Int64:
return strconv.FormatInt(f.Int(), 10)
case reflect.String:
return f.String()
case reflect.Bool:
if f.Bool() {
return "true"
}
return "false"
return ""
}
This works for the types above but I can't get it to work for time.Time
. How do I do this?
Judging from what you are trying to do, you don't really need reflection after getting the field. Here is a sample that works with time.Time
too.
package main
import (
"fmt"
"reflect"
"strconv"
"time"
)
func getField(v interface{}, field string) string {
r := reflect.ValueOf(v)
f := reflect.Indirect(r).FieldByName(field)
fieldValue := f.Interface()
switch v := fieldValue.(type) {
case int64:
return strconv.FormatInt(v, 10)
case int32:
return strconv.FormatInt(int64(v), 10)
case int:
return strconv.FormatInt(int64(v), 10)
case string:
return v
case bool:
if v {
return "true"
}
return "false"
case time.Time:
return v.String()
default:
return ""
}
}
type MyStruct struct {
Name string
Number int32
Is bool
Clock time.Time
}
func main() {
s := MyStruct{}
fmt.Println(getField(s, "Name"))
fmt.Println(getField(s, "Number"))
fmt.Println(getField(s, "Is"))
fmt.Println(getField(s, "Clock"))
}
Just for having an alternative solution, you can always hold kinds as vars and use them in a case.
var timeKind = reflect.TypeOf(time.Time{}).Kind()
func getField(v interface{}, field string) string {
r := reflect.ValueOf(v)
f := reflect.Indirect(r).FieldByName(field)
t := f.Kind()
switch t {
case reflect.Int, reflect.Int64:
return strconv.FormatInt(f.Int(), 10)
case reflect.String:
return f.String()
case reflect.Bool:
if f.Bool() {
return "true"
}
return "false"
case timeKind: // i am here!!!
// do whatever you want
return ""
}