go-踩坑点

go 遇到的一些问题

chan 关闭之后,还可以读写吗

不能写,但可以读

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package main

import (
"fmt"
"sync"
)

func main() {
var ret = make(chan []int, 1000)
var wg = sync.WaitGroup{}
wg.Add(3)
go func() {
defer wg.Done()
var result = make([]int, 0)
for i := 0; i < 10; i++ {
result = append(result, i)
}
ret <- result
}()
go func() {
defer wg.Done()
var result = make([]int, 0)
for i := 10; i < 20; i++ {
result = append(result, i)
}
ret <- result
}()
go func() {
defer wg.Done()
var result = make([]int, 0)
for i := 20; i < 30; i++ {
result = append(result, i)
}
ret <- result
}()
wg.Wait()
//go func() {
// for {
// ret <- []int{1}
// time.Sleep(time.Second)
// }
//}()
//close(ret)
for v := range ret { //0 range if v==0 break ,or panic
for _, v := range v {
fmt.Println(v)
}
}
}

并发获取数据,常见问题

1
2
3
4
5
6
7
8
9
10
11
for _,v:=range uids{
go func(){
fmt.Println(v)//v的值是一样的!
}()
}
==》
for _,v:=range uids{
go func(v int){
fmt.Println(v)//v的值正常
}(v)
}