On Thu, Aug 19, 2021 at 4:43 PM Денис Мухортов
<
muhorto...@gmail.com> wrote:
> I just started practicing with channels, after writing to the channel, nothing is output from there
> func main() {
> d := make(chan int)
> go factorial(5, d)
> time.Sleep(3 * time.Second)
> }
>
> func factorial(n int, d chan int) {
> fmt.Println("function starting...")
> time.Sleep(3 * time.Second)
> var a int = 1
> for ; n > 0; n-- {
> a *= n
> }
> d <- a // //nothing works after that
> fmt.Println(<-d)
> fmt.Println(a)
> }
Your main function can and probably does just return before the write
to d in factorial is performed. When the main function returns, the
process exits.
I suggest never to use time.Sleep as a synchronization mechanism. Not
even in experiments or throw away code. It may sometimes work, but it
is probably never correct. In either case, it makes reasoning about
the code hard, if not impossible, so proper synchronization is much
better for your understanding when you're "practicing with channels".
-j