无法识别来自 Switch 语句 golang 中的通道的字符串变量

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

这个函数是通过传递参数 m 从 goroutine 调用的。

m中发送的值为字符串:“01a”,语句Switch无法识别

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

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

当设置 m 时,开关工作正常

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

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

我怀疑频道会引入其他隐藏角色

不清楚您的代码试图做什么,提供的代码无效。 在提供的任一示例中,您都没有显示任何从通道读取的尝试,这两个示例都打开一个字符串,然后将一个新值分配给 msg_out (未声明)并将该值发送到通道。

如果没有完整的代码,就不可能知道哪里出错了,这里是一个简单的例子,它通过一个频道发送文本并再次读取它。希望这将澄清流程并确认字符串通过通道发送得很好。

如果您仍然无法正常工作,我认为您需要 post 完整的代码示例来获得帮助。

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)
}