Skip to content

Instantly share code, notes, and snippets.

@lalizita
Created August 21, 2024 21:51
Show Gist options
  • Save lalizita/9b3276bfc3c96733f6c334dca2cab5b1 to your computer and use it in GitHub Desktop.
Save lalizita/9b3276bfc3c96733f6c334dca2cab5b1 to your computer and use it in GitHub Desktop.
This code is a simple example of range over function and iterators in Go
package main
import (
"fmt"
"iter"
)
type Employee struct {
Name string
Salary int
}
var Employees = []Employee{
{Name: "Elliot", Salary: 4},
{Name: "Donna", Salary: 5},
}
func main() {
fmt.Println("Slice")
for k, v := range []int{2, 2, 2, 2} {
fmt.Printf("%d: %+v\n", k, v)
}
fmt.Println("Map")
m := map[int]string{
23: "lais",
13: "luana",
21: "luiz",
}
for k, v := range m {
fmt.Printf("%d: %+v\n", k, v)
}
fmt.Println("Function")
for i, employee := range Iterate(Employees) {
fmt.Printf("%d: %+v\n", i, employee)
}
}
func Iterate[Employee any](e []Employee) iter.Seq2[int, Employee] {
return func(yield func(int, Employee) bool) {
for i := 0; i <= len(e)-1; i++ {
if !yield(i, e[i]) {
return
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment