Search code examples
gosyntax-error

Why does my switch statement give me a syntax error?


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.


Solution

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