Search code examples
goswitch-statementchannelgoroutine

Does not recognize string variable coming from a channel in a Switch statement golang


This function is called from a goroutine by passing as parameter m.

The value sent in m is the string: "01a" and the statement Switch does not recognize

func myfunc(m string, c chan string) {
    defer close(c)

    switch m {
    case "01a":
       msg_out = "NO PASS"
    }
    c <- msg_out
}

when set m the Switch works fine

func myfunc(m string, c chan string) {
    defer close(c)

    m = "01a"
    switch m {
    case "01a":
        msg_out = "PASS"
    }
    c <- msg_out
}

I suspect the channel will introduce other hidden characters


Solution

  • It's not clear what your code is trying to do, the code provided is invalid. You haven't shown any attempt to read from the channel in either example provided, both examples switch on a string then assign a new value to msg_out (which is not declared) and send that value down a channel.

    Without the full code it's impossible to tell where you are going wrong, here is a simple example of sending text down a channel and reading it off again. Hopefully this will clarify the process and confirm that strings are sent over channels just fine.

    If you still cant get it working, I think you will need to post full code example to get help.

    Go playground

        package main
    
        import (
            "log"
            "time"
        )
    
        func main() {
    
            //make the channel
            strChan := make(chan string)
    
            //launch a goroutine to listen on the channel
            go func(strChan chan string) {
    
                //loop waiting for input on channel
                for {
                    select {
                    case myString := <-strChan:
                        // code to be run when a string is recieved here
    
                        // switch on actual contents of the string
                        switch myString {
                        case "I'm the expected string":
                            log.Println("got expected string")
                        default:
                            log.Println("not the string I'm looking for")
                        }
                    }
                }
            }(strChan)
    
            //sleep for a bit then send a string on the channel
            time.Sleep(time.Second * 2)
            strChan <- "I'm the expected string"
    
            //wait again, gives channel response a chance to happen  
            time.Sleep(time.Second * 2)
    }