-3

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.

2
  • 3
    The switch statement doesn't support channel communications, use select instead. Commented Mar 3, 2023 at 9:51
  • 2
    I think you want to write a select statement instead (replace switch with select). See go.dev/ref/spec#Select_statements. Commented Mar 3, 2023 at 9:52

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.