为什么我的 switch 语句会出现语法错误?

huangapple go评论80阅读模式
英文:

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 (
	&quot;fmt&quot;
)

func main() {
	writeMsgs := make(chan string)
	go sendMsgs(writeMsgs)
	for {
		switch{
		case msg := &lt;-writeMsgs:
			fmt.Println(msg)
		}
	}
}

func sendMsgs(writeMsgs chan string) {
	for i:=0;i&lt;5;i++ {
		writeMsgs&lt;-&quot;Test&quot;
	}
	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 := &lt;-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 := &lt;-writeMsgs:
            fmt.Println(msg)
        }
    }
}

Here you can play around with it.

huangapple
  • 本文由 发表于 2023年3月3日 17:46:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75625477.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定