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?
In Go, we can define new types by using the following form. In the syntax, type is a keyword. New type names must be identifiers. But please note that, type names declared at package level can't be init .
You can refer any data type in Go as an object. There are several data types provided by Go such as int8, int16, int32, int64, float64, string, bool etc.
Each data field in a struct is declared with a known type, which could be a built-in type or another user-defined type. Structs are the only way to create concrete user-defined types in Golang. Struct types are declared by composing a fixed set of unique fields.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With