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.
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.
CountWithFor
method uses a for-range
loop over an iter.Seq
. The V refers to the any type, which is any valid Go type.CountWithFor
method prints the total number of elements in the Seq
using a for-range
loop.iter.Seq
of any type, we can use the slices.Values
method from the slices module.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
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
.