英文:
Why does my switch statement give me a syntax error?
问题
我需要从通道中的字符串变量中获取数据,并在switch语句中使用。
package main
import (
"fmt"
)
func main() {
writeMsgs := make(chan string)
go sendMsgs(writeMsgs)
for {
select {
case msg := <-writeMsgs:
fmt.Println(msg)
}
}
}
func sendMsgs(writeMsgs chan string) {
for i := 0; i < 5; i++ {
writeMsgs <- "Test"
}
close(writeMsgs)
}
我已经参考了多个教程,但没有找到问题所在。
英文:
I need to get the string variable from the channel in a switch statement.
go version go1.19.6 linux/amd64
.\test.go:12:12: syntax error: unexpected :=, expecting :
package main
import (
"fmt"
)
func main() {
writeMsgs := make(chan string)
go sendMsgs(writeMsgs)
for {
switch{
case msg := <-writeMsgs:
fmt.Println(msg)
}
}
}
func sendMsgs(writeMsgs chan string) {
for i:=0;i<5;i++ {
writeMsgs<-"Test"
}
close(writeMsgs)
}
I have cross-referenced multiple tutorials and don't see where I am going wrong.
答案1
得分: 3
Go语言不允许将通道通信作为switch
语句的条件,你必须使用select
结构来代替,它非常相似。
> Golang的select语句类似于switch语句,用于多个通道的操作。该语句会阻塞,直到提供的任何一个case准备就绪。
在你的情况下,可以这样写:
func main() {
writeMsgs := make(chan string)
go sendMsgs(writeMsgs)
for {
select {
case msg := <-writeMsgs:
fmt.Println(msg)
}
}
}
你可以在这里进行测试。
英文:
Go does not allow channel communication as switch
case condition, you have to use a select
construct instead, which is very similar.
> Golang select statement is like the switch statement, which is used for multiple channels operation. This statement blocks until any of the cases provided are ready.
In your case it would be
func main() {
writeMsgs := make(chan string)
go sendMsgs(writeMsgs)
for {
select {
case msg := <-writeMsgs:
fmt.Println(msg)
}
}
}
Here you can play around with it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论