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

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

Linda Hamilton
发布: 2024-10-26 20:09:02
原创
156 人浏览过

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

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