Home  >  Article  >  Backend Development  >  golang traverse to delete elements

golang traverse to delete elements

王林
王林Original
2023-05-13 10:03:071194browse

In the Go language, traversing and deleting elements is a relatively common requirement. However, due to the special features of the Go language, some details need to be paid attention to. This article will introduce what you need to pay attention to when traversing and deleting elements in the Go language, and how to implement it correctly.

The slice and map data structures of Go language are very convenient to use. Slices can automatically expand, and maps can quickly access corresponding values ​​based on key values. These features make Go language very suitable for processing large amounts of data. However, when traversing slices and maps and deleting elements, you need to pay attention to the following issues.

  1. Traverse the slice to delete elements

When deleting elements in the slice, you need to pay attention to the following points:

1) Do not modify the slice during traversal

Directly deleting the slice during traversal will cause the index to become invalid, resulting in accidental deletion or missed deletion. For example:

func main() {
    nums := []int{1, 2, 3, 4, 5}
    for i, n := range nums {
        if n == 3 {
            nums = append(nums[:i], nums[i+1:]...)
        }
    }
    fmt.Println(nums) // 1 2 4 5
}

When the above code traverses to the element 3, it will be deleted. However, since the length and index of the slice were modified when deleting elements, the index of the subsequent elements changed. In fact, only the last element 4 of 3 was deleted, and 3 itself has not been deleted.

In order to avoid this situation, you can use another slice to record the subscript of the element to be deleted, and then perform the deletion operation after traversing. For example:

func main() {
    nums := []int{1, 2, 3, 4, 5}
    delIdx := []int{}
    for i, n := range nums {
        if n == 3 {
            delIdx = append(delIdx, i)
        }
    }
    for i, idx := range delIdx {
        nums = append(nums[:idx-i], nums[idx-i+1:]...)
    }
    fmt.Println(nums) // 1 2 4 5
}

In the above code, an empty slicedelIdx is first defined to record the subscript of the element to be deleted. When traversing nums, if the element to be deleted is found, the subscript of the element is added to delIdx. After the traversal is completed, delete nums.

2) Use "three pointers" to implement deletion

Another way to delete elements when traversing a slice is to use the "three pointers" method. That is, a pointer i is used to traverse the slice, a pointer j records the number of elements to be deleted, and a pointer k records the normal elements. The specific implementation is as follows:

func main() {
    nums := []int{1, 2, 3, 4, 5}
    j := 0
    for i := range nums {
        if nums[i] != 3 {
            nums[j] = nums[i]
            j++
        }
    }
    nums = nums[:j]
    fmt.Println(nums) // 1 2 4 5
}

In the above code, first define a pointer j to represent the number of elements to be deleted. Then use the pointer i to traverse the slice. If the current element does not need to be deleted, move it to the location of the pointer k, and then add 1 to k, indicating normal The number of elements is increased by 1. If the current element needs to be deleted, just skip it. After the traversal is completed, use nums[:j] to remove excess elements.

  1. Traverse the map to delete elements

In the Go language map, the operation of deleting elements is very simple. Just use the delete function. For example:

func main() {
    m := map[string]int{"a": 1, "b": 2, "c": 3, "d": 4}
    for k, v := range m {
        if v == 3 {
            delete(m, k)
        }
    }
    fmt.Println(m) // map[a:1 b:2 d:4]
}

Deleting elements when traversing the map will not cause index failure. Because the map is unordered, the position of each element does not matter. Therefore, just use the delete function directly during traversal.

It should be noted that the length of the map cannot be modified when traversing the map. For example, the following code will cause panic:

func main() {
    m := map[string]int{"a": 1, "b": 2, "c": 3, "d": 4}
    for k := range m {
        if k == "c" {
            m["e"] = 5
        }
        fmt.Println(m[k])
    }
}

When traversing to the element with the key c, the code adds a new key-value pair "e" to the map: 5. Because the length of the map changes, it will cause a runtime panic.

To sum up, the things you need to pay attention to when traversing and deleting elements in the Go language are:

1) When traversing a slice to delete elements, do not delete the slice directly. You should use another slice to record the subscript of the element to be deleted, and then perform the deletion operation after traversing; or use "three pointers" to implement deletion.

2) When traversing the map to delete elements, you can directly use the delete function without index failure. But the length of the map cannot be modified during traversal.

After mastering the above skills, we can correctly implement the operation of traversing and deleting elements in Go language.

The above is the detailed content of golang traverse to delete elements. 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
Previous article:golang interface to sliceNext article:golang interface to slice