此代码在 builti.go
中:
// 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
中挑选所有元素,但是我没有找到官方的解释。这是什么?
最佳答案
builtin.go 中的代码作为文档。代码未编译。
...
指定函数的最终参数是可变的。可变参数函数是 documented in the Go Language specification .简而言之,可以使用任意数量的最终参数调用可变参数函数。
Type part 是任何 Go 类型的替代品。
关于go - Go中 "...Type"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28512432/