Iter.Seq. Generics allow us to reuse a single function for many different argument types. With the iter.Seq type we can use a for-range loop over elements of a generic argument.
By receiving an iter.Seq instance in a function, we can use a for-loop. The slices.Values method in the slices package is a convenient way to get an iter.Seq from a slice.
Example. The goal of the iter package is to support for-loops over varying types of collections. This program introduces a generic method, CountWithFor, that receives an iter.Seq of any type.
Part 1 The CountWithFor method uses a for-range loop over an iter.Seq. The V refers to the any type, which is any valid Go type.
package main
import (
"iter""slices""fmt"
)
// Part 1: add generic function that loops over an iter.Seq of any type.
func CountWithFor[V any](seq iter.Seq[V]) {
count := 0
// Part 2: use for-loop over iter.Seq.
for _ = range seq {
count += 1
}
fmt.Println(count)
}
func main() {
// Part 3: get iter.Seq arguments from slices with Slice.Values, and use CountWithFor.
seq1 := slices.Values([]string{"bird", "frog", "dog"})
CountWithFor(seq1)
seq2 := slices.Values([]int{10, 20, 30, 40})
CountWithFor(seq2)
seq3 := slices.Values([]bool{false, true})
CountWithFor(seq3)
}3
4
2
Summary. The iter module, and its Seq type, provide a way to receive an iterable collection of any element. For a functioning program, we can use slices.Values along with iter.Seq.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.