Voici un petit programme d'échantillonnage qui fait ce que vous voulez:
package main
import (
"fmt"
"sort"
)
type friend struct {
name string
age int
}
func main() {
friends := []friend{
{"James", 44},
{"Jane", 47},
{"Bob", 30},
{"Cesar", 90},
{"John", 45},
}
over45 := filterFriends(friends, func(f friend) bool {
return f.age > 45
})
fmt.Println("over 45:", over45)
// note that sort.Sort will change the contents of the slice; if you want
// to keep the original order as well, you would first have to copy that
// slice and sort the copy
sort.Sort(byAge(friends))
fmt.Println("sorted by age:", friends)
}
// filterFriends takes your slice and a predicate to filter by, then returns a
// newly allocated list of friends that made it through the filter.
func filterFriends(friends []friend, pred func(friend) bool) []friend {
var fit []friend
for _, f := range friends {
if pred(f) {
fit = append(fit, f)
}
}
return fit
}
// byAge implements the sort.Interface so we can pass it to sort.Sort.
type byAge []friend
func (f byAge) Len() int { return len(f) }
func (f byAge) Less(i, j int) bool { return f[i].age < f[j].age }
func (f byAge) Swap(i, j int) { f[i], f[j] = f[j], f[i] }
la sortie du programme est:
over 45: [{Jane 47} {Cesar 90}]
sorted by age: [{Bob 30} {James 44} {John 45} {Jane 47} {Cesar 90}]
La comparaison directe serait une tranche de cartes, mais sans réelle problème que nous ne pouvons pas dire, ce qui est mieux. – JimB