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

Go 的可变参数函数可以变得更通用吗?

Susan Sarandon
发布: 2024-10-27 19:57:30
原创
955 人浏览过

 Can Go's Variadic Functions Be Made More Generic?

促进 Go 中的泛型可变参数函数

虽然 Go 可能不提供对泛型编程或函数重载的固有支持,但它在处理可变参数时确实允许一定程度的灵活性函数。

考虑一下常见场景,您有多个函数,如下所示:

<code class="go">func (this Document) GetString(name string, defaults ...string) string {
    // ... Function implementation
}

func (this Document) GetInt(name string, defaults ...int) int {
    // ... Function implementation
}</code>
登录后复制

您可能会遇到这些函数之间的代码重复。有没有办法最大限度地减少这种冗余?

是的,虽然 Go 缺乏通用模板,但您可以利用 interface{} 来提供通用解决方案。

<code class="go">func (this Document) Get(name string, defaults ...interface{}) interface{} {
    // ... Function implementation
    // This function returns `interface{}` instead of specific types.
}</code>
登录后复制

这种方法使您能够进行交互按以下方式使用该函数:

<code class="go">value := document.Get("index", 1).(int) // Type casting is required</code>
登录后复制

如果您喜欢空值,可以使用此方法:

<code class="go">value, ok := document.Get("index", 1).(int) // Returns `ok` to indicate type compatibility</code>
登录后复制

但是,此方法可能会产生运行时开销。建议评估您的代码结构并确定单独的函数或不同的解决方案是否更适合您的特定需求。

以上是Go 的可变参数函数可以变得更通用吗?的详细内容。更多信息请关注PHP中文网其他相关文章!

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