daily pastebin goal
36%
SHARE
TWEET

[Go] Concurrent generators.

cwchen Nov 28th, 2017 232 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.     "strings"
  6. )
  7.  
  8. func main() {
  9.     data := []string{
  10.         "The yellow fish swims slowly in the water",
  11.         "The brown dog barks loudly after a drink from its water bowl",
  12.         "The dark bird of prey lands on a small tree after hunting for fish",
  13.     }
  14.  
  15.     histogram := make(map[string]int)
  16.     wordsCh := make(chan string)
  17.  
  18.     go func() {
  19.         defer close(wordsCh)
  20.  
  21.         for _, line := range data {
  22.             words := strings.Split(line, " ")
  23.  
  24.             for _, word := range words {
  25.                 word = strings.ToLower(word)
  26.                 wordsCh <- word
  27.             }
  28.         }
  29.     }()
  30.  
  31.     for {
  32.         word, opened := <- wordsCh
  33.         if !opened {
  34.             break
  35.         }
  36.         histogram[word]++
  37.     }
  38.  
  39.     for k, v := range histogram {
  40.         fmt.Println(fmt.Sprintf("%s\t(%d)", k, v))
  41.     }
  42. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top