Go 里面 [...]string{"a", "b", "c"} 加三个点是什么骚写法?


本文摘自网络,作者,侵删。

看到 go/ast 源码包中有这么一段代码:

var objKindStrings = [...]string{
    Bad: "bad",
    Pkg: "package",
    Con: "const",
    Typ: "type",
    Var: "var",
    Fun: "func",
    Lbl: "label",
}

谷歌搜了一下,3 dots in 4 places 这篇文章介绍了“三点”语法在四个不同场景的使用。其中提到:

Array literals

In an array literal, the ... notation specifies a length equal to the number of elements in the literal.

stooges := [...]string{"Moe", "Larry", "Curly"} // len(stooges) == 3

看完我还没反应过来,这跟 []string 有啥区别?后来才注意到 array 字眼,天天用 slice 都忘了 array 的存在。

[...]string 是 array,而 []string 是 slice。[...]string[n]string 的便捷写法,n = arr 元素个数。

写段代码验证一下:

func main() {
   a := [...]string{"a", "b", "c", "d"}
   b := []string{"a", "b", "c", "d"}
   atype := reflect.TypeOf(a)
   btype := reflect.TypeOf(b)
   fmt.Println(atype.Kind(), atype)
   fmt.Println(btype.Kind(), btype)
}

输出:

array [4]string
slice []string

在这种常量场景用 [...] 还真是挺方便,修改元素个数,自动调整 array 长度。

至于为什么用 array 而不是 slice,应该是出于性能考虑,slice 封装自 array 之上,虽然使用便捷,但是数据结构更复杂,性能也更差。Go 源码作者真是细节到位。

你学废了吗?


本文来自:Segmentfault

感谢作者:.container .card .information strong

查看原文:Go 里面 [...]string{"a", "b", "c"} 加三个点是什么骚写法?

相关阅读 >>

[concurrent-map]-并发map在Go中的使用

Go语言 break 语句

Golang 时间的格式化格式的含义

Golang封装解析请求参数(使用不同的请求头)

词法分析器

大型迷惑现场之[]*t是什么?*[]t是什么?*[]*t又是什么?

Golang读取文本乱码解决方法

手撸Golang 行为型设计模式 访问者模式

手撸Golang 行为型设计模式 责任链模式

Go 为什么比php性能高

更多相关阅读请进入《Go》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...