var resultChan = make(chan string)
如下代码为什么会从channel :resultChan中读到很多空字符串 ?
```
go func() {
for i := 1; i < 101; i++ {
if i%2 == 0 {
resultChan <- fmt.Sprintf("success")
} else {
resultChan <- fmt.Sprintf("数字%d不是偶数", i)
}
}
}()
length := 0
var err []string
go func() {
for {
select {
case r := <-resultChan:
length += 1
if r == "success" {
if length == 100 {
close(resultChan)
done <- true
}
} else if r == "" {
fmt.Println("读到空字符串")
} else {
err = append(err, r)
}
}
}
}()
<-done
if len(err) > 0 {
for _, v := range err {
fmt.Println(v)
}
}
```
case r ,ok:= <-resultChan:
if !ok {
fmt.Println("结束")
return
}
...
#2
更多评论
var err []string
go func() {
for {
time.Sleep(time.Microsecond) // 加个休眠
select {
case r := <-resultChan:
length += 1
if r == "success" {
if length == 100 {
close(resultChan)
done <- true
}
} else if r == "" {
fmt.Printf("读到空字符串")
} else {
err = append(err, r)
}
}
}
}()
猜测是执行太快了,select有空就读chan,若读不到则返回chan对应type的默认值。
#1