go - Filtering a slice of structs based on a different slice in Golang -
in example code below, have few users in manysimpleusers
remove manyfullusers
based on username.
if nested couple of for... range
loops, there many cycles required filter of elements, when there large numbers of elements in both slices.
what best way achieve in go?
package main import "fmt" func main() { fmt.println("hello, playground") type fulluser struct { username string useremail string } manyfullusers := []fulluser{{"foo", "foo@jawohl.com"}, {"bar", "bar@jawohl.com"}, {"baz", "baz@jawohl.com"}} type simpleuser struct { username string } manysimpleusers := []simpleuser{{"foo"}, {"bar"}} fmt.println(manyfullusers) fmt.println(manysimpleusers) }
create map use filter.
func filterbyusername(fu []fulluser, su []simpleuser) (out []fulluser) { f := make(map[string]struct{}, len(su)) _, u := range su { f[u.username] = struct{}{} } _, u := range fu { if _, ok := f[u.username]; ok { out = append(out, u) } } return }
Comments
Post a Comment