简体   繁体   中英

What is the meaning of “…Type” in Go?

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?

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 aredocumented 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM