首页  >  文章  >  后端开发  >  Go如何在没有模板的情况下实现通用可变参数函数?

Go如何在没有模板的情况下实现通用可变参数函数?

Linda Hamilton
Linda Hamilton原创
2024-10-26 20:09:02145浏览

 How Can Go Achieve Generic Variadic Functions Without Templates?

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
}

// etc. for various types</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>

GetValueFromDb函数也应该返回一个interface{}。在客户端代码中,可以使用类型断言来转换和获取值:

<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