flatmap.go 641 B

12345678910111213141516171819202122232425262728293031
  1. package main
  2. import (
  3. "fmt"
  4. "github.com/tal-tech/go-zero/core/mr"
  5. )
  6. var (
  7. persons = []string{"john", "mary", "alice", "bob"}
  8. friends = map[string][]string{
  9. "john": {"harry", "hermione", "ron"},
  10. "mary": {"sam", "frodo"},
  11. "alice": {},
  12. "bob": {"jamie", "tyrion", "cersei"},
  13. }
  14. )
  15. func main() {
  16. var allFriends []string
  17. for v := range mr.Map(func(source chan<- interface{}) {
  18. for _, each := range persons {
  19. source <- each
  20. }
  21. }, func(item interface{}, writer mr.Writer) {
  22. writer.Write(friends[item.(string)])
  23. }, mr.WithWorkers(100)) {
  24. allFriends = append(allFriends, v.([]string)...)
  25. }
  26. fmt.Println(allFriends)
  27. }