关闭陈死锁

I would like to understand why this case deadlock and why it's not in the other case.

If I close the channel inside the goroutine, it works fine, but if I close it after the WaitGroup.Wait() it cause a deadlock.

package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "sync"
)

var (
    wg    = sync.WaitGroup{}
    links = make(chan string)
)

func rec_readdir(depth int, path string) {
    files, _ := ioutil.ReadDir(path)
    for _, f := range files {
        if symlink, err := os.Readlink(path + "/" + f.Name()); err == nil {
            links <- path + "/" + symlink
        }
        rec_readdir(depth+1, path+"/"+f.Name())
    }
    if depth == 0 {
        wg.Done()
        // close(links) // if close here ok
    }
}

func main() {
    wg.Add(1)
    go rec_readdir(0, ".")

    for slink := range links {
        fmt.Println(slink)
    }
    wg.Wait()
    close(links) // if close here deadlock
}

https://play.golang.org/p/Ntl_zsV5nwO

for slink := range links will continue looping until the channel is closed. So you obviously can't close after that loop. When you do, you get a deadlock, as you have observed.