Question

I have an assignment to use arrays of channels.

I do not understand. Why this does not work?

package main

import "fmt"

func run() {
    chann[0] <- 1
}

var chann = make([]chan int, 2)

func main() {
    go run()
    obj := <- chann[0]
    fmt.Println(obj)
}
Was it helpful?

Solution

You have initialized the array of channels, but not the channels themselves.

As for why it deadlocks; this is due to the fact that a channel value that has not been initalised, or has been set to nil will always block. (See this article)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top