Go common mistakes

  1. defer

    1
    2
    3
    4
    5
    6
    7
    func main() {
    for {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()
    time.Sleep(time.Minute)
    }
    }

    defer 会在函数退出时才执行,以上会造成内存泄漏

  2. select

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13

    func main() {
    ch1 := make(chan int)
    ch2 := make(chan int)
    for {
    select {
    case <-ch1:
    // do something
    default:
    break
    }
    }
    }

    select里的break是让select继续执行,而非外层的for

  3. for and goroutine

    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
    package main

    import "fmt"

    func main() {
    arr := []string{"hello", "world"}
    for _, item := range arr {
    go say1(&item)
    go say2(item)
    }
    ch := make(chan int)
    <-ch
    }
    func say1(s *string) {
    fmt.Printf("in say1 %s, addr: %p\n", *s, s)
    }

    func say2(s string) {
    fmt.Printf("in say2 %s, addr: %p\n", s, &s)
    }

    // in say2 world, addr: 0xc000010280
    // in say2 hello, addr: 0xc000094000
    // in say1 world, addr: 0xc000010250
    // in say1 world, addr: 0xc000010250
    // fatal error: all goroutines are asleep - deadlock!

    // goroutine 1 [chan receive]:
    // main.main()
    // /tmp/sandbox3927361405/prog.go:15 +0x1bf

    // Program exited.

    for range 里面的item在遍历的时候,每次被赋一个新的值,但是本身的地址是不会变的,可理解为下面的代码

    1
    2
    3
    4
    5
    6
    var item string
    for i:=0;i<len(arr);i++ {
    item = arr[i]
    go say1(&item)
    go say2(item)
    }

    say1里用的是指针访问,在每个say1执行的时候,item可能已经被赋了新的值,即 world