Search code examples
gotype-assertion

Solution for type assertion without generics with Golang?


I'm using gorm, and it allows many data types like int, uint, int8, uint8 ....

Then I have a plugin in template like this:

f["UNIX2STR"] = func(t interface{}, f string) string {
        switch t.(type) {
        case int:
            return time.Unix(int64(t.(int)), 0).Format(f)
        case uint:
            return time.Unix(int64(t.(uint)), 0).Format(f)
        case uint8:
            return time.Unix(int64(t.(uint8)), 0).Format(f)
        case *int:
            return time.Unix(int64(*t.(*int)), 0).Format(f)
        case *uint:
            return time.Unix(int64(*t.(*uint)), 0).Format(f)
        case *uint8:
            return time.Unix(int64(*t.(*uint8)), 0).Format(f)
        .....
        default:
            return ""
        }
        // return time.Unix(int64(t), 0).Format(f)
    }

It converts all integer types to formatted string. So what am I suppose to do? List all gorm supported int types and cast it to int64?

I have searched many days for solution convert interface{} to its true type without using type assertion but didn't work.


Solution

  • I've not used gorm, but I think that something like this could solve your problem:

    func formatUnix(t interface{}, f string) (string, error) {
        timestampStr := fmt.Sprint(t)
        timestamp, err := strconv.ParseInt(timestampStr, 10, 64)
        if err != nil {
            return "", err
        }
        return time.Unix(timestamp, 0).Format(f), nil
    }
    

    Rather than listing all potential types, it simply converts the interface{} to a string using fmt.Sprint() and then convert the string to int64 using strconv.ParseInt().