Today I Learned
Search…
Creating Python's `next()` alternative using Go Closures
If you don't know what next() in python means, the below code illustrates it.
1
MCU_Movies = iter(["Iron Man", "Thor", "Captain America: The first Avenger"])
2
x = next(MCU_Movies)
3
print(x, end="\n")
4
x = next(MCU_Movies)
5
print(x, end="\n")
6
x = next(MCU_Movies)
7
print(x)
Copied!
So if you had guess this would print
1
Iron Man
2
Thor
3
Captain America: The first Avenger
Copied!
The next() function is used to get the next item in an iterator.
Go doesn't have a next method (nor the concept of iterators actually) so we will try to achieve something similar using Closures.
  • A closure is implemented through a anonymous(function with no name) function, basically closure is an instance of function.
  • In Go functions are first class citizens, meaning we can do all sort of things with them, assign them to a variable, pass as an argument to another function.
Below is a naive implementation of how this could look in Go. Ping me if you have a better way to do this ;)
1
package main
2
​
3
import "fmt"
4
​
5
/*
6
nextIterator returns another function, which we define anonymously in the body of nextIterator.
7
The returned function closes over the variable index to form a closure.
8
*/
9
func nextIterator(array []int) func() int {
10
index := -1
11
​
12
return func() int{
13
index++
14
return array[index]
15
}
16
}
17
func main() {
18
​
19
// an integer array
20
var prices = []int{7, 1, 5}
21
​
22
// create an instance of the anonymous function. i.e, a closue
23
next := nextIterator(prices)
24
​
25
// call the closure
26
fmt.Println(next())
27
fmt.Println(next())
28
fmt.Println(next())
29
​
30
}
Copied!
See this demo on Go Playground.
Copy link
Edit on GitHub