Home >Backend Development >Golang >How to add elements to slices in Go language

How to add elements to slices in Go language

青灯夜游
青灯夜游Original
2023-01-10 14:06:123231browse

In the Go language, you can use append() to dynamically add elements to a slice. append() can append one element, multiple elements, or a new slice to a slice. The syntax is "append(slice, element 1, element 2...)" or "append(slice, new slice...)". When using the append() function to dynamically add elements to a slice, if there is insufficient space to accommodate enough elements, the slice will be "expanded", and the length of the new slice will change.

How to add elements to slices in Go language

The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.

In the Go language, you can use append() to dynamically add elements to a slice.

Go language append() function

append can append one element, multiple elements, and new slices to a slice

var a []int
a = append(a, 1) // 追加1个元素
a = append(a, 1, 2, 3) // 追加多个元素, 手写解包方式
a = append(a, []int{1,2,3}...) // 追加一个切片, 切片需要解包

However, it should be noted that when using the append() function to dynamically add elements to a slice, if there is insufficient space to accommodate enough elements, the slice will be "expanded". At this time, the length of the new slice Changes will occur.

When a slice is expanded, the capacity expansion rule is to expand by 2 times the capacity, such as 1, 2, 4, 8, 16..., the code is as follows:

var numbers []int


for i := 0; i < 10; i++ {
    numbers = append(numbers, i)
    fmt.Printf("len: %d  cap: %d pointer: %p\n", len(numbers), cap(numbers), numbers)
}

The code output is as follows :

How to add elements to slices in Go language

The code description is as follows:

  • Line 1 declares an integer slice.

  • Line 4, loop adds 10 numbers to the numbers slice.

  • Line 5, print out the length, capacity and pointer changes of the slice, use the function len() to view the number of elements the slice has, and use the function cap() to view the capacity of the slice .

By looking at the code output, we can find an interesting rule: the slice length len is not equal to the slice capacity cap.

The process of continuously adding elements to a slice is similar to a company moving. In the early days of the company's development, funds were tight and there were few employees, so only a small room was needed to accommodate all employees. As the business grew, Expansion and increase in income require the expansion of workstations, but the size of the office space is fixed and cannot be changed. Therefore, the company can only choose to move, and every time it moves, all personnel need to be transferred to a new office location.

  • Employees and workstations are elements in the slice.

  • The office is the allocated memory.

  • Moving means reallocating memory.

  • No matter how many times you move, the company name will never change, and the variable name representing the external slice will not change.

  • Since the address changes after moving, the memory "address" will also be modified.

In addition to appending at the end of the slice, we can also add elements at the beginning of the slice:

var a = []int{1,2,3}
a = append([]int{0}, a...) // 在开头添加1个元素
a = append([]int{-3,-2,-1}, a...) // 在开头添加1个切片

Adding elements at the beginning of the slice will generally cause memory reallocation, and This will cause all existing elements to be copied once. Therefore, the performance of adding elements from the beginning of the slice is much worse than appending elements from the tail.

Because the append function returns the characteristics of the new slice, the slice also supports chain operations. We can combine multiple append operations to insert elements in the middle of the slice:

var a []int
a = append(a[:i], append([]int{x}, a[i:]...)...) // 在第i个位置插入x
a = append(a[:i], append([]int{1,2,3}, a[i:]...)...) // 在第i个位置插入切片

Each add The second append call in the operation creates a temporary slice, copies the contents of a[i:] to the newly created slice, and then appends the temporarily created slice to a[:i].

【Related recommendations: Go video tutorial, Programming teaching

The above is the detailed content of How to add elements to slices 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