go - Go中 "...Type"是什么意思?

标签 go

此代码在 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/

相关文章:

mysql - 默认时间戳在不同的mysql表中具有不同的时区

google-app-engine - 在 Google App Engine 中处理 HTTPS 请求

docker - 如何在 docker go 客户端中创建具有内存限制的容器

go - 努力用gogradle编译go项目

function - 通过Go中的查找表在对象中创建变量的函数

go - 数组中的引用类型

oracle - 获取最后插入的id(go + oracle)

google-app-engine - 谷歌数据存储全局连接

使用 GoConvey 测试 REST API

pointers - 要在 for 循环中使用 goroutine,为什么迭代指向结构的指针而不是结构本身有效