Home > database >  golang how to cover an interface type (always basic type) to string
golang how to cover an interface type (always basic type) to string

Time:08-19

I coded this function to cover the variable:

func parseValueToString(vv interface{}) string {
    switch v := vv.(type) {
    case int:
        return fmt.Sprintf("%d", v)
    case float64:
        return fmt.Sprintf("%f", v)
    case bool:
        return fmt.Sprintf("%t", v)
    case string:
        return v
    }

    panic("not support type")
}

but when it was int8,int32,int64,float32 etc..., it will be cased to panic.
I knew that I can add case int8, case int16 ..., but is there some more elegant way to do this?

I am using go1.18

CodePudding user response:

you could use fmt.Sprintf(), it works like fmt.Printf except that it returns the formatted string.

You could code your function as

func parseValueToString(vv interface{}) string {
    return fmt.Sprintf("%s", vv)
}

of course you could also directly call fmt.Sprintf() instead of making a function that calls it

CodePudding user response:

is there some more elegant way to do this?

No.

  •  Tags:  
  • go
  • Related