0

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

}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Ungrace
  • 214
  • 2
  • 12
  • 2
    Close of nil channel sounds more like the channel is not initialized (nil) or already closed (never tried that in code to see what it says). So it looks properly closed. I do not see init code for room.Quit though. – Norbert Oct 07 '20 at 19:26

1 Answers1

3

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).

icza
  • 389,944
  • 63
  • 907
  • 827