这个函数是通过传递参数 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 发送得很好。
如果您仍然无法正常工作,我认为您需要发布完整的代码示例以获得帮助。
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/