当通道未关闭时,为什么没有死锁?

Go RunTime writes to the pipe, then it does not close the pipe, and afterwards, it executes normally.

Why is there no deadlock when the channel is not closed?

package main

import (
    `fmt`
    `time`
)

func product(num int) chan int {
    ch := make(chan int, 1)

    go func(num int) {
        for i := 0; i < num; i++ {
            ch <- i
        }
    }(num)

    return ch
}

func main() {
    in := product(100)

    go func() {
        for v := range in {
            fmt.Println(v)
        }
    }()

    time.Sleep(time.Second)
}

// 0 1 2 3 4 5 ...

Because there is no situation when two goroutines wait for each other and non of them can proceed its execution.

You read from the channel in a separate (non-main) goroutine, in the meantime the main goroutine is not blocked and exits as soon as the timer reaches 1 second.

If you would move the read for loop to the main goroutine, then you will get the deadlock error. Because in this case the program will be blocked forever as the channel from which you are trying to read is not closed and nobody writes into it anymore.

See also Deadlock between goroutines