英文:
What is the meaning of "...Type" in Go?
问题
这段代码是关于builti.go
的:
// append是内置函数,用于将元素追加到切片的末尾。如果切片有足够的容量,目标切片会被重新切片以容纳新的元素。如果没有足够的容量,将会分配一个新的底层数组。
// append返回更新后的切片。因此,通常需要将append的结果存储在保存切片本身的变量中:
// slice = append(slice, elem1, elem2)
// slice = append(slice, anotherSlice...)
// 作为一个特例,可以将字符串追加到字节切片中,像这样:
// 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
中选择所有的元素,但我还没有找到官方的解释。它是什么意思?
英文:
This code is in 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
The last line made me feel very confused. I do not know the meaning of ...Type
.
These are other codes:
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)
}
The result is
[1 2] [3 4 5] [1 2 3 4 5]
I guess the function of ...
is to pick all elements from elems
, but I haven't found an official explanation. What is it?
答案1
得分: 21
builtin.go中的代码用作文档。该代码未编译。
...
指定函数的最后一个参数是可变参数。可变参数函数在Go语言规范中有文档记录。简而言之,可变参数函数可以使用任意数量的参数调用最后一个参数。
Type部分是任何Go类型的替代。
英文:
The code in builtin.go serves as documentation. The code is not compiled.
The ...
specifies that the final parameter of the function is variadic. Variadic functions are documented in the Go Language specification. In short, variadic functions can be called with any number of arguments for the final parameter.
The Type part is a stand-in for any Go type.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论