go - 无法识别来自 Switch 语句 golang 中的 channel 的字符串变量

标签 go switch-statement channel goroutine

这个函数是通过传递参数 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
}

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

最佳答案

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

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

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

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

关于go - 无法识别来自 Switch 语句 golang 中的 channel 的字符串变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45775183/

相关文章:

javascript - 外部 JavaScript 和下拉菜单无法在浏览器中正确呈现

java - 使用 channel 将数据从 outputStream 传递到 bytebuffer

docker - 为什么 dockerfile RUN 中创建的文件不在主机上,我已经挂载主机目录进行服务

javascript - Switch 语句未按预期工作

golang 传递 http.ResponseWriter

batch-file - 对 cmd/批处理文件中的所有问题切换为 "yes"

c# - 处理进入故障状态的持久性 WCF 客户端

go - 使用 ticker 的 golang 代码有什么问题

unit-testing - 测试一个 go 闭包

google-app-engine - 使用 Go、App Engine、专用内存缓存和实例内存实现分片计数器