Last active
February 29, 2024 23:25
-
-
Save kahlys/86dc89cd1f3a69253cd306a9827df2b3 to your computer and use it in GitHub Desktop.
golang filters on struct arrays using generics
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
// https://go2goplay.golang.org/p/YF6fsuohucV | |
package main | |
import ( | |
"fmt" | |
"strings" | |
) | |
type Array struct { | |
Elements []Element | |
} | |
type Element struct { | |
Name string | |
Age int | |
} | |
func Filter[T any](s []T, cond func(t T) bool) []T { | |
res := []T{} | |
for _, v := range s { | |
if cond(v) { | |
res = append(res, v) | |
} | |
} | |
return res | |
} | |
func main() { | |
a := Array{ | |
Elements: []Element{ | |
{Name: "Batman", Age: 39}, | |
{Name: "Superman", Age: 42}, | |
{Name: "WonderWoman", Age: 15000}, | |
}, | |
} | |
b := Filter(a.Elements, func(e Element) bool { | |
return strings.Contains(strings.ToLower(e.Name), strings.ToLower("woman")) | |
}) | |
fmt.Println(b) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment