How to remove every N‑th element from a slice in Go

1 Answer

0 votes
// ------------------------------------------------------------
// A small program demonstrating how to remove every Nth element
// from a slice using clear, expressive Go patterns.
// ------------------------------------------------------------

package main

import (
    "fmt"
)

/*
    removeEveryNth returns a new slice with every Nth element removed.

    Go slices use zero‑based indexing, so we check (index + 1) % n != 0
    to keep elements that are *not* in the Nth position.

    The variable "size" captures the slice length before the loop,
    which avoids repeatedly accessing len(items) inside the loop.

    A new slice is allocated up front with enough capacity to avoid
    repeated growth operations.
*/
func removeEveryNth[T any](items []T, n int) []T {
    if n <= 0 {
        panic("n must be a positive integer")
    }

    size := len(items)          // capture size once
    result := make([]T, 0, size) // preallocate capacity

    for i := 0; i < size; i++ {
        if (i+1)%n != 0 {
            result = append(result, items[i])
        }
    }

    return result
}

/*
    main demonstrates the function with a simple example.
    Keeping main small and focused makes the program easy to extend.
*/
func main() {
    data := make([]int, 0, 20)
    for i := 1; i <= 20; i++ {
        data = append(data, i) // Example slice: numbers 1–20
    }

    n := 3 // Remove every 3rd element

    cleaned := removeEveryNth[int](data, n)

    fmt.Println("Original:", data)
    fmt.Println("After removing every", n, "-th element:", cleaned)
}


/*
run:

Original: [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20]
After removing every 3-th element: [1 2 4 5 7 8 10 11 13 14 16 17 19 20]

*/

 



answered Aug 15 by avibootz
...