Last active
August 5, 2018 04:02
-
-
Save withattribution/c78770ef871790d3474b6c159710fc29 to your computer and use it in GitHub Desktop.
video: https://youtu.be/5IKcPMJXkKs?t=1091 and blog: https://medium.com/capital-one-developers/closures-are-the-generics-for-go-cb32021fb5b5 playground: https://play.golang.org/p/g2KBbxCc35c
This file contains hidden or 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" | |
| ) | |
| type Employee struct { | |
| Id int | |
| Name string | |
| } | |
| type Person struct { | |
| Age int | |
| Name string | |
| } | |
| type PetOwner struct { | |
| Person | |
| Pet string | |
| } | |
| func FilterPerson(ps []Person, name string) []Person { | |
| var out []Person | |
| for _, v := range ps { | |
| if v.Name == name { | |
| out = append(out, v) | |
| } | |
| } | |
| return out | |
| } | |
| func NameFilter(length int, name string, | |
| nameFinder func(int) string, | |
| populator func(int)) { | |
| for i := 0; i < length; i++ { | |
| if nameFinder(i) == name { | |
| populator(i) | |
| } | |
| } | |
| } | |
| func main() { | |
| fmt.Println("Hello, playground") | |
| peeps := []Person{ | |
| Person{27, "samantha"}, | |
| Person{37, "tom"}, | |
| } | |
| var nameFilteredPersons []Person | |
| NameFilter(len(peeps), "tom", | |
| func(i int) string { | |
| return peeps[i].Name | |
| }, func(i int) { | |
| nameFilteredPersons = append(nameFilteredPersons, peeps[i]) | |
| }) | |
| fi := FilterPerson(peeps, "tom") | |
| fmt.Println(fi) | |
| fmt.Println("generics with side effects!") | |
| fmt.Println(nameFilteredPersons) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment