Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go type switch with `time.Time`

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?

like image 316
fiskeben Avatar asked Sep 04 '26 08:09

fiskeben


1 Answers

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"))
}
like image 75
Arman Ordookhani Avatar answered Sep 07 '26 05:09

Arman Ordookhani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!