Created
August 21, 2024 21:51
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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