Go Range over function example
In the new Go language version 1.22.0, the ‘function iterators’ experiment was introduced. Let’s try a simple example of the new functionality.
Setup
Install go version 1.22.0
If you use vscode, add the env to .vscode/launch.json file:
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch Package",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${fileDirname}",
"env": {
"GOEXPERIMENT": "rangefunc"
}
}
]
}Iterator for slice of strings example
Create main.go file, init module with go mod init sampleiter
Get Roman Shirokov’s stories in your inbox
Join Medium for free to get updates from this writer.
First import new experimental iter package.
package main
import (
"fmt"
"iter" // Assuming 'iter' is the experimental package for the iterator proposal
)Define a function IterateStrings that takes a slice of strings and returns an iterator (iter.Seq[string]) for iterating over the slice.
func IterateStrings(slice []string) iter.Seq[string] Inside the function, it returns an anonymous function (which matches the Seq type definition) that takes a yield function as a parameter.
return func(yield func(string) bool) The for loop iterates over each string in the slice, calls the yield function with the string. If the yield function returns false, it breaks the loop, allowing termination in the end of sequence.
for _, str := range slice {
if !yield(str) { // Yield each string until false
break
}
}In the main function define slice with data and for loop over IterateStrings .
func main() {
// Example slice of strings
myStrings := []string{"Go", "Rangefunc", "Experiment"}
// Using the iterator with the range-over-function syntax
for str := range IterateStrings(myStrings) {
fmt.Println(str) // Prints each string in the slice
}
}Full example:
package main
import (
"fmt"
"iter" // Assuming 'iter' is the experimental package for the iterator proposal
)
func IterateStrings(slice []string) iter.Seq[string] {
return func(yield func(string) bool) {
for _, str := range slice {
if !yield(str) {
break
}
}
}
}
func main() {
myStrings := []string{"Go", "Rangefunc", "Experiment"}
// Using the iterator with the range-over-function syntax
for str := range IterateStrings(myStrings) {
fmt.Println(str)
}
}To run it: GOEXPERIMENT=rangefunc go run main.go or run with vscode
Output:
Go
Rangefunc
ExperimentLinks
Implementation: https://go.googlesource.com/go/+/refs/changes/41/510541/7/src/cmd/compile/internal/rangefunc/rewrite.go
Wiki description: https://go.dev/wiki/RangefuncExperiment





