首页 > 后端开发 > Golang > 正文

如何在Go中实现可变参数函数的泛型编程?

Susan Sarandon
发布: 2024-10-28 07:47:30
原创
258 人浏览过

How to Achieve Generic Programming for Variadic Functions in Go?

Go 中可变参数函数的泛型编程

尽管 Go 缺乏模板和重载函数,但仍然可以实现某种形式的泛型编程对于可变参数函数。

考虑以下示例,其中包含一系列函数,这些函数从数据库检索值,并在请求的值丢失时返回默认值:

<code class="go">func (this Document) GetString(name string, defaults ...string) string {
    v, ok := this.GetValueFromDb(name)
    if !ok {
        if len(defaults) >= 1 {
            return defaults[0]
        } else {
            return ""
        }
    }
    return v.asString
}

func (this Document) GetInt(name string, defaults ...int) int {
    v, ok := this.GetValueFromDb(name)
    if !ok {
        if len(defaults) >= 1 {
            return defaults[0]
        } else {
            return 0
        }
    }
    return v.asInt
}</code>
登录后复制

消除代码冗余,可以使用interface{}类型实现通用的Get()函数:

<code class="go">func (this Document) Get(name string, defaults ...interface{}) interface{} {
    v, ok := this.GetValueFromDb(name)
    if !ok {
        if len(defaults) >= 1 {
            return defaults[0]
        } else {
            return 0
        }
    }
    return v
}</code>
登录后复制

在客户端代码中,可以对返回值进行相应的类型转换:

<code class="go">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</code>
登录后复制

但是,这种方法由于类型转换而引入了一些运行时开销。仍然建议考虑重构代码或针对不同类型使用单独的函数。

以上是如何在Go中实现可变参数函数的泛型编程?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!