views:

94

answers:

1

Since I've a similar function for 2 different data types:

func GetStatus(value uint8) (string) {...}
func GetStatus(name string) (string) {...}

I would want to use a way more simple like:

func GetStatus(value interface{}) (string) {...}

Is possible to create a generic function using an interface? The data type could be checked using reflect.Typeof(value)

+1  A: 

Does what you want to do need the complexity and overhead of the reflect package? Have you considered a simple switch statement type switch?

package main

import (
    "fmt"
)

func GetStatus(value interface{}) string {
    var s string
    switch v := value.(type) {
    case uint8:
        v %= 85
        s = string(v + (' ' + 1))
    case string:
        s = v
    default:
        s = "error"
    }
    return s
}

func main() {
    fmt.Println(GetStatus(uint8(2)), GetStatus("string"), GetStatus(float(42.0)))
}
peterSO