How to use append() in go language

青灯夜游
Release: 2023-01-28 09:03:37
Original
3431 people have browsed it

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)
Copy after login

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增加两倍
}
Copy after login

Output result:

s1=[火鸡面 辛拉面 汤达人] len(s1)=3 cap(s1)=3
s1=[火鸡面 辛拉面 汤达人 小当家] len(s1)=4 cap(s1)=6
Copy after login

(2)append() appends a slice
slice = append(slice,anotherSlice...)
Copy after login

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))
}
Copy after login

Output result:

s1=[火鸡面 辛拉面 汤达人] len(s1)=3 cap(s1)=3
s1=[火鸡面 辛拉面 汤达人 小当家] len(s1)=4 cap(s1)=6
s1=[火鸡面 辛拉面 汤达人 小当家 脆司令 圣斗士] len(s1)=6 cap(s1)=6
Copy after login

(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))
	} 
}
Copy after login

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
Copy after login

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: ] )
Copy after login

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)
}
Copy after login

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]
Copy after login

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)
}
Copy after login

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]
Copy after login
[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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template