Skip to content

Instantly share code, notes, and snippets.

@kahlys
Last active February 29, 2024 23:25
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kahlys/86dc89cd1f3a69253cd306a9827df2b3 to your computer and use it in GitHub Desktop.
Save kahlys/86dc89cd1f3a69253cd306a9827df2b3 to your computer and use it in GitHub Desktop.
golang filters on struct arrays using generics
// 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