Home Backend Development Golang golang slice addition and deletion

golang slice addition and deletion

May 22, 2023 pm 04:19 PM

Golang slice is a very commonly used data structure. It is a dynamic array that supports automatic expansion and can easily operate and modify data in the program. The length of the slice can be changed dynamically, which provides a lot of flexibility to our code. Adding and deleting elements is a very common operation during the use of slice. This article will introduce how to add and delete elements in golang slice.

  1. Basic operations of golang slice

Let’s first review the basic operations of golang slice in order to better understand the process of adding and deleting elements. In golang, to define a slice, you need to use the make function. This function contains three parameters. The first one specifies the type of the slice, the second one specifies the length of the slice, and the third one specifies the capacity of the slice.

For example:

var s = make([]int, 3, 5)
Copy after login

The above code defines an int type slice with a length of 3 and a capacity of 5. The first parameter is the int type we defined, and the second The first parameter specifies the length of the slice to be 3, and the third parameter specifies the capacity of the slice to be 5. It should be noted that the capacity of a slice can be greater than the length, but the length cannot be greater than the capacity.

Next are some basic operations of golang slice:

1) Access the slice element

var s = []int {1, 2, 3, 4, 5}
fmt.Println(s[0])  // 输出1
Copy after login

2) Modify the slice element

var s = []int {1, 2, 3, 4, 5}
s[0] = 6
fmt.Println(s)  // 输出[6 2 3 4 5]
Copy after login

3) Get the slice The length and capacity

var s = make([]int, 3, 5)
fmt.Println(len(s))  // 输出3
fmt.Println(cap(s))  // 输出5
Copy after login

4) Slicing operation

var s = []int {1, 2, 3, 4, 5}
fmt.Println(s[1:3])  // 输出[2 3]
Copy after login
  1. Golang slice element adding operation

In golang, slice element adding operation is Two ways are to use the append function and the " " operator.

Below, we will introduce the usage of these two methods respectively.

1) Use the append function to add elements

In golang, we can use the append function to dynamically add slice elements. Its syntax is as follows:

func append(s []T, vs ...T) []T
Copy after login

Among them, the first parameter s is a slice of type T, and the following parameter vs is a variable parameter list, also of type T, indicating the element to be added. The return value of this function is a new slice containing the added elements.

For example:

var s = []int {1, 2, 3, 4, 5}
s = append(s, 6)
fmt.Println(s)  // 输出[1 2 3 4 5 6]
Copy after login

In the above code, we use the append function to add an element 6 to the slice, and then save the result back to the original slice.

If we want to add multiple elements to the slice, we only need to pass in these elements after the append function. For example:

var s = []int {1, 2, 3, 4, 5}
s = append(s, 6, 7, 8)
fmt.Println(s)  // 输出[1 2 3 4 5 6 7 8]
Copy after login

It should be noted that if the capacity of the slice is insufficient, the append function will automatically expand its capacity, so its time complexity is O(1).

2) Use the " " operator to add elements

In addition to using the append function, you can also use the " " operator in golang to merge two slices. The operands of this operator are all slices, and the result is also a new slice.

For example, as shown below:

var s1 = []int {1, 2, 3}
var s2 = []int {4, 5, 6}
s := s1 + s2
fmt.Println(s)  // 输出[1 2 3 4 5 6]
Copy after login

In this example, we add two slices and get a new slice s. It should be noted that the time complexity of the " " operator is O(n), because it requires opening a new array and copying the elements of the two slices into the new array.

  1. Element deletion operation of golang slice

If you want to delete an element in the golang slice, there are two methods, namely using the append function and using the copy function.

1) Use the append function to delete elements

We can use the append function's slicing operation to intercept the element to be deleted and the elements behind it, and then use the append function to recombine them. The specific implementation is as follows:

func Remove(slice []int, idx int) []int {
    return append(slice[:idx], slice[idx+1:]...)
}

func main() {
    var s = []int {1, 2, 3, 4, 5}
    s = Remove(s, 2)
    fmt.Println(s)  // 输出[1 2 4 5]
}
Copy after login

In this code, we use the Remove function to delete the third element in the slice. First, we combine the elements from slice0 to idx-1 and the elements from slice idx 1 to the end into a new slice. Then, we use the append function to save this new slice back to the original slice. Because the append function will automatically expand the capacity, there is no need to worry about insufficient capacity of the new slice.

It should be noted that the time complexity of this method is O(n), because it needs to copy n-1 elements to a new slice.

2) Use the copy function to delete elements

In addition to using the append function, we can also use the copy function to delete elements in the golang slice. The copy function can copy the elements in the src slice to the dst slice and return the number of copied elements.

The specific implementation is as follows:

func Remove(slice []int, idx int) []int {
    copy(slice[idx:], slice[idx+1:])
    return slice[:len(slice)-1]
}

func main() {
    var s = []int {1, 2, 3, 4, 5}
    s = Remove(s, 2)
    fmt.Println(s)  // 输出[1 2 4 5]
}
Copy after login

In this code, we use the Remove function to delete the third element in the slice. Use the copy function to copy all elements after idx 1 to the idx position, and then reduce the length of the original slice by 1.

It should be noted that the time complexity of this method is also O(n), because it needs to copy n-1 elements to a new slice.

  1. Summary

This article mainly introduces the operations of adding and deleting elements in golang slice. You can use the append function and " " operator to add elements, and you can use the append function and copy function to delete elements.

It is recommended to choose different methods according to the specific situation in actual programming. If you want to add or delete a small number of elements, it is more convenient to use the append function or the " " operator; if you want to add or delete a large number of elements, it is more efficient to use the copy function.

The above is the detailed content of golang slice addition and deletion. For more information, please follow other related articles on the PHP Chinese website!

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the vulnerabilities of Debian OpenSSL What are the vulnerabilities of Debian OpenSSL Apr 02, 2025 am 07:30 AM

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

How do you write unit tests in Go? How do you write unit tests in Go? Mar 21, 2025 pm 06:34 PM

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

How do you use the pprof tool to analyze Go performance? How do you use the pprof tool to analyze Go performance? Mar 21, 2025 pm 06:37 PM

The article explains how to use the pprof tool for analyzing Go performance, including enabling profiling, collecting data, and identifying common bottlenecks like CPU and memory issues.Character count: 159

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

PostgreSQL monitoring method under Debian PostgreSQL monitoring method under Debian Apr 02, 2025 am 07:27 AM

This article introduces a variety of methods and tools to monitor PostgreSQL databases under the Debian system, helping you to fully grasp database performance monitoring. 1. Use PostgreSQL to build-in monitoring view PostgreSQL itself provides multiple views for monitoring database activities: pg_stat_activity: displays database activities in real time, including connections, queries, transactions and other information. pg_stat_replication: Monitors replication status, especially suitable for stream replication clusters. pg_stat_database: Provides database statistics, such as database size, transaction commit/rollback times and other key indicators. 2. Use log analysis tool pgBadg

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

See all articles