Skip to content

Instantly share code, notes, and snippets.

@thomd

thomd/filter.go

Last active Sep 7, 2020
Embed
What would you like to do?
Go Examples #golang #go #code
package model
import (
"fmt"
)
type Person struct {
Name string
Age int
}
func (p *Person) String() string {
return fmt.Sprintf("%v (%v)", p.Name, p.Age)
}
type PersonToBool func(*Person) bool
type PersonList []*Person
func (pl PersonList) Filter(f PersonToBool) PersonList {
var ret []*Person
for _, p := range pl {
if f(p) {
ret = append(ret, p)
}
}
return ret
}
// USAGE
//
// var pl model.PersonList
// pl = append(pl, &model.Person{Name: "Jane", Age: 32})
// pl = append(pl, &model.Person{Name: "Joe", Age: 27})
// pl2 := pl.Filter(func(p *model.Person) bool {
// return p.Age > 30
// })
// for _, p := range pl2 {
// fmt.Println(p)
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment