Nth element. 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.
Example code. This Go program has a custom function called everyNthElement. It only accepts string slices, but this detail can be changed to any other type.
Step 1 In everyNthElement, we create an empty string slice. This is where the "kept" elements are placed.
Step 2 We use a for-range loop over the string slice that was passed in as an argument.
Step 3 We use a modulo division to determine if we are on the "nth" element we want to keep.
Step 4 We return the result slice. This will contain all the retained elements.
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]
Results. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.