samedi 3 octobre 2015

golang string channel send/receive inconsistency

New to go. I'm using 1.5.1. I'm trying to accumulate a word list based on an incoming channel. However, my input channel (wdCh) is sometimes getting the empty string ("") during testing. I'm perplexed. I'd rather not have a test for the empty string before I add its accumulated count in my map. Feels like a hack to me.

package accumulator

import (
    "fmt"
    "http://ift.tt/1qjqyGz"
    "testing"
)

var words map[string]int

func Accumulate(wdCh chan string, closeCh chan bool) {
    words = make(map[string]int)
    for {
        select {
        case word := <-wdCh:
            fmt.Printf("word = %s\n", word)
            words[word]++
        case <-closeCh:
            return
        }
    }
}

func pushWords(w []string, wdCh chan string) {
    for _, value := range w {
        fmt.Printf("sending word = %s\n", value)
        wdCh <- value
    }
    close(wdCh)
}

func TestAccumulate(t *testing.T) {
    sendWords := []string{"one", "two", "three", "two"}
    wMap := make(map[string]int)
    wMap["one"] = 1
    wMap["two"] = 2
    wMap["three"] = 1

    wdCh := make(chan string)
    closeCh := make(chan bool)

    go Accumulate(wdCh, closeCh)
    pushWords(sendWords, wdCh)

    closeCh <- true
    close(closeCh)

    assert.Equal(t, wMap, words)
}

Aucun commentaire:

Enregistrer un commentaire