使用接口的通用功能

时间:2010-05-09 10:10:02

标签: function interface generics go

因为我对2种不同的数据类型有类似的功能:

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

我想使用更简单的方式:

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

是否可以使用界面创建通用功能? 可以使用reflect.Typeof(value)

检查数据类型

1 个答案:

答案 0 :(得分:2)

您想要做的是否需要reflect包的复杂性和开销?您是否考虑过简单的switch声明type切换?

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