9

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

 3 years ago
source link: https://studygolang.com/articles/33305
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

看到 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 源码作者真是细节到位。

你学废了吗?

有疑问加站长微信联系(非本文作者)

eUjI7rn.png!mobile

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK