频道没有正常关闭?
Channel is not closing properly?
根据我在这里与遇到类似问题的人一起阅读的内容,显然,频道没有关闭。我尝试了多种关闭频道的方法,但仍然出现此错误。
预期行为:当我在控制台中键入“QUIT”时,程序会无错误地退出
当前行为:当我在控制台中键入“QUIT”时,出现此错误
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
这是代码。
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
}
频道的 Zero value 是 nil
,关闭 nil
频道会出现恐慌,正如您所经历的那样。
Closing the nil
channel also causes a run-time panic.
您尝试关闭 room.Quit
,但您从未为其分配任何值。
像这样创建 room
时执行此操作:
room := room{
MessageCH: make(chan string),
Quit: make(chan struct{}),
}
通道公理见
另请注意,它不会在此处引起问题,但您不应完全按照其类型命名变量:room := room{...}
。在此声明之后,您不能再引用 room
类型,该标识符将被隐藏(直到包含块的末尾)。
根据我在这里与遇到类似问题的人一起阅读的内容,显然,频道没有关闭。我尝试了多种关闭频道的方法,但仍然出现此错误。
预期行为:当我在控制台中键入“QUIT”时,程序会无错误地退出
当前行为:当我在控制台中键入“QUIT”时,出现此错误
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
这是代码。
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
}
Zero value 是 nil
,关闭 nil
频道会出现恐慌,正如您所经历的那样。
Closing the
nil
channel also causes a run-time panic.
您尝试关闭 room.Quit
,但您从未为其分配任何值。
像这样创建 room
时执行此操作:
room := room{
MessageCH: make(chan string),
Quit: make(chan struct{}),
}
通道公理见
另请注意,它不会在此处引起问题,但您不应完全按照其类型命名变量:room := room{...}
。在此声明之后,您不能再引用 room
类型,该标识符将被隐藏(直到包含块的末尾)。