首页  >  文章  >  后端开发  >  如何在 Go 中使用可变参数函数实现泛型编程?

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

Barbara Streisand
Barbara Streisand原创
2024-10-26 12:21:29777浏览

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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn