Go中的通用编程?

我知道Go不支持模板或重载函数,但是我想知道是否有任何方法可以进行某种通用编程?


我有很多这样的功能:


func (this Document) GetString(name string, default...string) string {

    v, ok := this.GetValueFromDb(name)

    if !ok {

        if len(default) >= 1 {

            return default[0]

        } else {

            return ""

        }

    }

    return v.asString

}


func (this Document) GetInt(name string, default...int) int {

    v, ok := this.GetValueFromDb(name)

    if !ok {

        if len(default) >= 1 {

            return default[0]

        } else {

            return 0

        }

    }

    return v.asInt

}


// etc. for many different types

没有太多冗余代码,有什么办法可以做到这一点?


慕森卡
浏览 190回答 2
2回答

繁星点点滴滴

您最多可以实现interface{}类型的用法,如下所示:func (this Document) Get(name string, default... interface{}) interface{} {    v, ok := this.GetValueFromDb(name)    if !ok {        if len(default) >= 1 {            return default[0]        } else {            return 0        }    }    return v}GetValueFromDb函数也应该调整为返回interface{}值,而不是像现在这样的一些包装器。然后,在客户端代码中,您可以执行以下操作:value := document.Get("index", 1).(int)  // Panics when the value is not int或者value, ok := document.Get("index", 1).(int)  // ok is false if the value is not int但是,这将产生一些运行时开销。我最好坚持使用单独的功能,并尝试以某种方式重组代码。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go