Since I've a similar function for 2 different data types:
func GetStatus(value uint8) (string) {...}
func GetStatus(name string) (string) {...}
I would want t开发者_如何学Goo 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)
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)))
}
精彩评论