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

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

Barbara Streisand
发布: 2024-10-26 12:21:29
原创
795 人浏览过

How Can You Achieve Generic Programming with 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{} 类型:

<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 nil
        }
    }
    return v
}</code>
登录后复制

然后可以将这个通用函数与 type 一起使用客户端代码中的断言:

<code class="go">value := document.Get("index", 1).(int)  // Panics if the value is not an int</code>
登录后复制

<code class="go">value, ok := document.Get("index", 1).(int)  // `ok` is false if the value is not an int</code>
登录后复制

但是,这种方法会引入运行时开销。在某些情况下,保留单独的函数并考虑重构代码可能会更有效。

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

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