开发者

Generic function using an interface

开发者 https://www.devze.com 2022-12-29 21:45 出处:网络
Since I\'ve a similar function for 2 different data types: func GetStatus(value uint8) (string) {...} func GetStatus(name string) (string) {...}

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)))
}
0

精彩评论

暂无评论...
验证码 换一张
取 消