This is a creation in Article, where the information may have evolved or changed.
Merging slice, like merging arrays, is a more common operation. After the C + + operator overload in the image, it is possible to use the plus sign directly. Golang Resolute not. Start with the copy solution first.
func copy(dst, src []Type) int
Never used this function, the return value append is not the same, and returns the number of copies. And only for slice operations, other types are not supported. As can be seen in the parameter table, two parameters must be of the same type and cannot be the same as []Type []interface{} this form. This function is not appended to the dst back, but is copied from the beginning. If you want to append to the back, you also need to indicate location information. copycomplete code of the merged array implemented:
a := []int{1, 2, 3, 4}b := []int{5, 6, 7}c := make([]int, len(a)+len(b))copy(c, a)copy(c[len(a):], b)
In copy the process, if there dst is not enough space, the space is not automatically appended. Therefore, you should apply for a sufficient amount of space before merging. Then it is duplicated two times. The second copy also needs to indicate the slice location to prevent being overwritten.
This code, although functional, but always feel more dirty. It was later discovered that the parameters of the append function were supported by variable-length parameter types.
func append(slice []Type, elems ...Type) []Type
In this way, three lines of complex code become a line:
a := []int{1, 2, 3, 4}b := []int{5, 6, 7}d := append(a, b...)
Reference results:
0xfeee1f740xfeee1f38[1 2 3 4 5 6 7]0xfeee1f2c[1 2 3 4 5 6 7]0xfeee1f20[5]
Please refer to the complete source code in this article.
Recently in see effective Go, feel good, recommend to everyone.
Reference documents
- "1" slice delete one or more items-go Chinese Community
- "2" Go language merge Slice-Dada's homepage
- "3" Package builtin-the Go Programming Language
- "4" Array and slice (Slice)-ice
- "5" Go slices:usage and Internals-the go Blog
- "6" See Paradigm Golang (14)-variadic function-G_will ' s Blog
Original link: Golang--append variable parameters, reproduced please indicate the source!