In the Go language, the append() function is used to dynamically add elements to a slice. You can add elements to the end of the slice and return the result; when calling the append function, you must use the original slice variable to receive the return value and append an element. You can use the "slice = append(slice,elem1,elem2)" statement. To append a slice, you can use the "slice = append(slice,anotherSlice...)" statement.
The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.
Go language’s built-in function append() can dynamically add elements to a slice.
Points:
- append() is used to add elements to the end of the slice and return the result.
- When calling the append function, you must use the original slice variable to receive the return value
- append appends elements. If the slice still has capacity, it will be The new elements are placed in the remaining space behind the original slice. When the underlying array cannot be assembled, Go will create a new underlying array to save the slice, and the slice address will also change accordingly.
- After assigning a new address, copy the elements in the original slice one by one to the new slice and return.
(1) append() appends an element slice = append(slice,elem1,elem2)
append Within the brackets, multiple parameters can be added after the first parameter slice. package main import "fmt" //切片进阶操作 func main(){ //append()为切片追加元素 s1 := []string {"火鸡面","辛拉面","汤达人"} fmt.Printf("s1=%v len(s1)=%d cap(s1)=%d\n",s1,len(s1),cap(s1)) //调用append函数必须用原来的切片变量接收返回值 s1 = append(s1,"小当家") //append追加元素,原来的底层数组装不下的时候,Go就会创建新的底层数组来保存这个切片 fmt.Printf("s1=%v len(s1)=%d cap(s1)=%d\n",s1,len(s1),cap(s1))//cap增加两倍 }Output result:
s1=[火鸡面 辛拉面 汤达人] len(s1)=3 cap(s1)=3 s1=[火鸡面 辛拉面 汤达人 小当家] len(s1)=4 cap(s1)=6
(2)append() appends a sliceslice = append(slice,anotherSlice...)
append There can only be two parameters in the brackets, one slice, another appended slice. package main import "fmt" //切片进阶操作 func main(){ //append()为切片追加元素 s1 := []string {"火鸡面","辛拉面","汤达人"} fmt.Printf("s1=%v len(s1)=%d cap(s1)=%d\n",s1,len(s1),cap(s1)) //调用append函数必须用原来的切片变量接收返回值 s1 = append(s1,"小当家") //append动态追加元素,原来的底层数组容纳不下足够多的元素时,切片就会开始扩容,Go底层数组就会把底层数组换一个 fmt.Printf("s1=%v len(s1)=%d cap(s1)=%d\n",s1,len(s1),cap(s1)) //调用append添加一个切片 s2 := []string{"脆司令","圣斗士"} s1 = append(s1,s2...)//...表示拆开切片,再添加 fmt.Printf("s1=%v len(s1)=%d cap(s1)=%d",s1,len(s1),cap(s1)) }Output result:
s1=[火鸡面 辛拉面 汤达人] len(s1)=3 cap(s1)=3 s1=[火鸡面 辛拉面 汤达人 小当家] len(s1)=4 cap(s1)=6 s1=[火鸡面 辛拉面 汤达人 小当家 脆司令 圣斗士] len(s1)=6 cap(s1)=6
(3) When using make to create a slice, it is a common mistake to use append() to add elements package main
import "fmt"
func main(){
var a = make([]int, 5, 10)
fmt.Println(a)
fmt.Printf("%p\n",a)
for i := 0; i <10; i++ {
a = append(a,i)
//%p 打印切片地址
fmt.Printf("%v,%p,cap(a):%d\n",a,a,cap(a))
}
}
Output result : [0 0 0 0 0] 0xc0000180a0 [0 0 0 0 0 0],0xc0000180a0,cap(a):10 [0 0 0 0 0 0 1],0xc0000180a0,cap(a):10 [0 0 0 0 0 0 1 2],0xc0000180a0,cap(a):10 [0 0 0 0 0 0 1 2 3],0xc0000180a0,cap(a):10 [0 0 0 0 0 0 1 2 3 4],0xc0000180a0,cap(a):10 [0 0 0 0 0 0 1 2 3 4 5],0xc00007c000,cap(a):20 [0 0 0 0 0 0 1 2 3 4 5 6],0xc00007c000,cap(a):20 [0 0 0 0 0 0 1 2 3 4 5 6 7],0xc00007c000,cap(a):20 [0 0 0 0 0 0 1 2 3 4 5 6 7 8],0xc00007c000,cap(a):20 [0 0 0 0 0 0 1 2 3 4 5 6 7 8 9],0xc00007c000,cap(a):20Note: (1) make creates a slice, and if there is a default length, there will be a default value. Append() adds elements after the default value, rather than overwriting the default value. (2) When the element exceeds the capacity of 10 set when make is created, and the original bottom layer cannot be assembled, a new continuous address will be used to store the element.
(4) Use append to delete elements
Go does not provide a function to specifically delete elements, but deletes elements through the characteristics of the slice itself. That is, taking the deleted element as the dividing point, and then using append to reconnect the memory of the two parts before and after. For example:
If you want to delete an element in slice s, the index of the deleted element is index, then the deletion process is
s = append ( s[ :index ], s[ index+1: ] )Reconnects the two parts before and after. In essence, it moves the element at the deleted point forward and reconnects the memory.
package main import "fmt" func main(){ a1 := [...]int{1,2,5,3,78,9,4,9,23,32} s1 := a1[:] //得到切片 fmt.Println(s1) //删除索引为4的78 s1 = append(s1[:4],s1[5:]...) fmt.Println(s1) fmt.Println(a1) }The principle of using append to delete elements in Go is: (The painting is not ugly at all...)
[1 2 5 3 78 9 4 9 23 32] [1 2 5 3 9 4 9 23 32] [1 2 5 3 9 4 9 23 32 32]After understanding, you can try to guess what the output of the following program is:
package main import "fmt" func main(){ a1 := [...]int{1,2,5,3,78,9,4,9,23,32} s1 := a1[:] //得到切片 fmt.Println(s1) //删掉索引为2和3的5,3 s1 = append(s1[:2],s1[4:]...) fmt.Println(s1) fmt.Println(a1) }
[1 2 5 3 78 9 4 9 23 32] [1 2 78 9 4 9 23 32] [1 2 78 9 4 9 23 32 23 32][Related recommendations:
Go video tutorial, Programming teaching】
The above is the detailed content of How to use append() in go language. For more information, please follow other related articles on the PHP Chinese website!

Go uses the "encoding/binary" package for binary encoding and decoding. 1) This package provides binary.Write and binary.Read functions for writing and reading data. 2) Pay attention to choosing the correct endian (such as BigEndian or LittleEndian). 3) Data alignment and error handling are also key to ensure the correctness and performance of the data.

The"bytes"packageinGooffersefficientfunctionsformanipulatingbyteslices.1)Usebytes.Joinforconcatenatingslices,2)bytes.Bufferforincrementalwriting,3)bytes.Indexorbytes.IndexByteforsearching,4)bytes.Readerforreadinginchunks,and5)bytes.SplitNor

Theencoding/binarypackageinGoiseffectiveforoptimizingbinaryoperationsduetoitssupportforendiannessandefficientdatahandling.Toenhanceperformance:1)Usebinary.NativeEndianfornativeendiannesstoavoidbyteswapping.2)BatchReadandWriteoperationstoreduceI/Oover

Go's bytes package is mainly used to efficiently process byte slices. 1) Using bytes.Buffer can efficiently perform string splicing to avoid unnecessary memory allocation. 2) The bytes.Equal function is used to quickly compare byte slices. 3) The bytes.Index, bytes.Split and bytes.ReplaceAll functions can be used to search and manipulate byte slices, but performance issues need to be paid attention to.

The byte package provides a variety of functions to efficiently process byte slices. 1) Use bytes.Contains to check the byte sequence. 2) Use bytes.Split to split byte slices. 3) Replace the byte sequence bytes.Replace. 4) Use bytes.Join to connect multiple byte slices. 5) Use bytes.Buffer to build data. 6) Combined bytes.Map for error processing and data verification.

Go's encoding/binary package is a tool for processing binary data. 1) It supports small-endian and large-endian endian byte order and can be used in network protocols and file formats. 2) The encoding and decoding of complex structures can be handled through Read and Write functions. 3) Pay attention to the consistency of byte order and data type when using it, especially when data is transmitted between different systems. This package is suitable for efficient processing of binary data, but requires careful management of byte slices and lengths.

The"bytes"packageinGoisessentialbecauseitoffersefficientoperationsonbyteslices,crucialforbinarydatahandling,textprocessing,andnetworkcommunications.Byteslicesaremutable,allowingforperformance-enhancingin-placemodifications,makingthispackage

Go'sstringspackageincludesessentialfunctionslikeContains,TrimSpace,Split,andReplaceAll.1)Containsefficientlychecksforsubstrings.2)TrimSpaceremoveswhitespacetoensuredataintegrity.3)SplitparsesstructuredtextlikeCSV.4)ReplaceAlltransformstextaccordingto


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 English version
Recommended: Win version, supports code prompts!

Atom editor mac version download
The most popular open source editor
