Consider a slice in Go that contains many elements, but we want to only retain every second or third element. We can develop a special function for this purpose.
And with an argument, we can specify the interval of elements we want to keep. This function can help when we want to only process some parts of a slice.
This Go program has a custom function called everyNthElement
. It only accepts string
slices, but this detail can be changed to any other type.
everyNthElement
, we create an empty string
slice. This is where the "kept" elements are placed.for-range
loop over the string
slice that was passed in as an argument.package main import ( "fmt" ) func everyNthElement(values []string, n int) []string { // Step 1: create empty slice. result := []string{} // Step 2: enumerate the input slice. for i, value := range values { // Step 3: if index of element is evenly divisible by n, append it. if i % n == 0 { result = append(result, value) } } // Step 4: return the result slice. return result } func main() { // Use the function on this slice. values := []string{"a", "b", "c", "d", "e", "f", "g", "h", "i"} result := everyNthElement(values, 2) fmt.Println(result) result = everyNthElement(values, 3) fmt.Println(result) }[a c e g i] [a d g]
We can see with the argument of 2, every other element is skipped over. And with an argument of 3, we skip over 2 elements between additions to the result.
By implementing an every "nth" element function, we learn about modulo division, enumerating slices, and appending to slices. The nth-element code can be useful in occasional real-world programs.