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 } 

playground


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -