Channel is not closing properly?

Issue

From what I’ve read on here with people who’ve had similar problems, apparently, a channel isn’t closing. I’ve tried multiple ways of closing the channels but I still get this error.

Expected behavior: when I type "QUIT" into the console, exit the program without errors

current behavior: when I type "QUIT" into the console, I get this error

panic: close of nil channel 
goroutine 6 [running]:
 main.main.func1(0xc000010200, 0xc00006e060, 0x0, 0x0)
    /home/greg/go/src/challenges/hydraChat/simplechat/simpleChat.go:24 +0xd7
created by main.main
    /home/greg/go/src/challenges/hydraChat/simplechat/simpleChat.go:18 +0x88
exit status 2

Here is the code.

type room struct {
MessageCH chan string
People    map[chan<- string]struct{}
Quit      chan struct{}

}

func main() {
    room := room{MessageCH: make(chan string)}
    enter code here
    var msg string

    go func() {
        for {
            fmt.Scan(&msg)

            room.MessageCH <- msg
            if msg == "QUIT" {
                close(room.Quit)
                return
            }
        }

    }()
    go func() {
        for msg := range room.MessageCH {
            fmt.Println("message received: ", msg)
        }
        defer close(room.MessageCH)
    }()

    <-room.Quit

}

Solution

Zero value for channels is nil, and closing a nil channel panics just as you experienced.

Spec: Close:

Closing the nil channel also causes a run-time panic.

You try to close room.Quit, yet you never assign any value to it.

Do it when you create room like this:

room := room{
    MessageCH: make(chan string),
    Quit:      make(chan struct{}),
}

For channel axioms see How does a non initialized channel behave?

Also note that it doesn’t cause problems here but you should not name a variable exactly as its type: room := room{...}. After this declaration you can’t refer to the room type anymore, that identifier will be shadowed (till the end of the containing block).

Answered By – icza

Answer Checked By – Mildred Charles (GoLangFix Admin)

Leave a Reply

Your email address will not be published.