在Go语言中,“...Type”是什么意思?

17
这段代码在文件中:
// The append built-in function appends elements to the end of a slice. If
// it has sufficient capacity, the destination is resliced to accommodate the
// new elements. If it does not, a new underlying array will be allocated.
// Append returns the updated slice. It is therefore necessary to store the
// result of append, often in the variable holding the slice itself:
//  slice = append(slice, elem1, elem2)
//  slice = append(slice, anotherSlice...)
// As a special case, it is legal to append a string to a byte slice, like this:
//  slice = append([]byte("hello "), "world"...)
func append(slice []Type, elems ...Type) []Type

最后一行让我感到非常困惑。我不知道...Type的含义。

这些是其他代码:

package main

import "fmt"

func main() {
   s := []int{1,2,3,4,5}
   s1 := s[:2]
   s2 := s[2:]
   s3 := append(s1, s2...)
   fmt.Println(s1, s2, s3)
}

结果是

[1 2] [3 4 5] [1 2 3 4 5]

我猜测...函数的作用是从elems中选择所有元素,但我没有找到官方解释。它是什么?
1个回答

22
在builtin.go中的代码作为文档。该代码未被编译。
"..."指定函数的最终参数是可变参数。可变参数函数在Go语言规范中有documented。简而言之,可变参数函数可以使用任意数量的参数调用最后一个参数。
"Type"部分是任何Go类型的代替。

2
这里有一篇关于切片的绝佳文章,可能会对您有所帮助:https://github.com/golang/go/wiki/SliceTricks - Joe Bergevin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接