Reputation: 2607
I have a small snippet of code like this
func main() {
var c chan string
go func() {
c <- "let's get started"//write1
//c <- "let's get started"//write2
//c <- "let's get started"//write3
fmt.Println("wrote the stuff....")
}()
//time.Sleep(3 * time.Second) //adding this always shows fatal exception
c = make(chan string)
fmt.Println(<-c)
}
I do not see the output wrote the stuff....
on console if I uncomment //write2
and write3
code snippet lines. I understand that probably I don't see it is because the channel is unbuffered and totally synchronous, and there is only one read happening outside the channel. However, when program exits, the go routine is blocked, why is there no error like deadlocked...
or something in this case that I see?
Upvotes: 3
Views: 89
Reputation: 131
This is an interesting experiment. I don't know if its possible but this type of error should be caught by the compiler, there should be a feature that checks at the compile-time if anything is writing in a nil
channel.
Upvotes: -2
Reputation: 280778
Create the channel before you try to write to it. If the func
goroutine tries to send elements through c
before there's actually a channel there, it ends up using a nil channel, which blocks forever.
Upvotes: 6