Reputation: 8103
package main
import "fmt"
import "time"
func main() {
c := make(chan int)
c <- 42 // write to a channel
val := <-c // read from a channel
println(val)
}
I think c <- 42
put 42 to channel c, then val := <-c
put value in c to val.
but why does it get deadlock?
Upvotes: 1
Views: 81
Reputation: 43899
You have created an unbuffered channel. So the statement c <- 42
will block until some other goroutine tries to receive a value from the channel. Since no other goroutine is around to do this, you got a deadlock. There are two ways you could fix this:
c := make(chan int, 1)
would allow you to send a single value on the channel without blocking.Upvotes: 5