search
HomeBackend DevelopmentGolangHow to use append() in go language

How to use append() in go language

Jan 18, 2023 pm 03:31 PM
golanggo language

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.

How to use append() in go language

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 slice
slice = 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):20

Note:

(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...)

How to use append() in go language

Output result:

[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)
}

How to use append() in go language

Correct result:

[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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Learn Go Binary Encoding/Decoding: Working with the 'encoding/binary' PackageLearn Go Binary Encoding/Decoding: Working with the 'encoding/binary' PackageMay 08, 2025 am 12:13 AM

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.

Go: Byte Slice Manipulation with the Standard 'bytes' PackageGo: Byte Slice Manipulation with the Standard 'bytes' PackageMay 08, 2025 am 12:09 AM

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

Go encoding/binary package: Optimizing performance for binary operationsGo encoding/binary package: Optimizing performance for binary operationsMay 08, 2025 am 12:06 AM

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

Go bytes package: short reference and tipsGo bytes package: short reference and tipsMay 08, 2025 am 12:05 AM

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.

Go bytes package: practical examples for byte slice manipulationGo bytes package: practical examples for byte slice manipulationMay 08, 2025 am 12:01 AM

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 Binary Encoding/Decoding: A Practical Guide with ExamplesGo Binary Encoding/Decoding: A Practical Guide with ExamplesMay 07, 2025 pm 05:37 PM

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.

Go 'bytes' Package: Compare, Join, Split & MoreGo 'bytes' Package: Compare, Join, Split & MoreMay 07, 2025 pm 05:29 PM

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

Go Strings Package: Essential Functions You Need to KnowGo Strings Package: Essential Functions You Need to KnowMay 07, 2025 pm 04:57 PM

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

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SecLists

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

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 new version

SublimeText3 Linux latest version

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Atom editor mac version download

Atom editor mac version download

The most popular open source editor