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

Josh Jameson
  • 80
  • 1
  • 4
  • 3
    The `switch` statement doesn't support _channel communications_, use [`select`](https://go.dev/ref/spec#Select_statements) instead. – mkopriva Mar 03 '23 at 09:51
  • 2
    I think you want to write a select statement instead (replace `switch` with `select`). See https://go.dev/ref/spec#Select_statements. – Zeke Lu Mar 03 '23 at 09:52

1 Answers1

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.

Mattia Righetti
  • 1,265
  • 1
  • 18
  • 31