How to Efficiently Remove Elements from a Slice in a Loop in Go?

Barbara Streisand
Release: 2024-10-31 06:21:02
Original
602 people have browsed it

How to Efficiently Remove Elements from a Slice in a Loop in Go?

In-Place Element Removal Within a Slice Loop

Problem:

Accessing slice elements from i within a range for loop and removing them using append() is problematic. Incrementing the loop variable (i) may skip subsequent elements after removal, leading to incomplete processing.

Best Practices:

1. Manual Loop Variable Decrementation

Use a regular for loop with manual loop variable (i) decrementing when an element is removed:

<code class="go">for i := 0; i < len(a); i++ {
    if conditionMeets(a[i]) {
        a = append(a[:i], a[i+1:]...)
        i--
    }
}
Copy after login

2. Downward Loop

Alternatively, use a downward loop to avoid manual decrementation:

<code class="go">for i := len(a) - 1; i >= 0; i-- {
    if conditionMeets(a[i]) {
        a = append(a[:i], a[i+1:]...)
    }
}</code>
Copy after login

3. Non-Removable Element Copying

If numerous elements need to be removed, consider copying non-removable elements to a new slice to improve efficiency:

<code class="go">b := make([]string, len(a))
copied := 0
for _, s := range(a) {
    if !conditionMeets(s) {
        b[copied] = s
        copied++
    }
}
b = b[:copied]</code>
Copy after login

4. In-Place Copying and Zeroing

For general-purpose in-place removal, maintain two indices and assign non-removable elements while zeroing removed element spaces:

<code class="go">copied := 0
for i := 0; i < len(a); i++ {
    if !conditionMeets(a[i]) {
        a[copied] = a[i]
        copied++
    }
}
for i := copied; i < len(a); i++ {
    a[i] = "" // Zero places of removed elements
}
a = a[:copied]</code>
Copy after login

The above is the detailed content of How to Efficiently Remove Elements from a Slice in a Loop in Go?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!