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-- } }
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>
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>
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>
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!