通过传递参数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时,Switch工作正常
func myfunc(m string, c chan string) {
defer close(c)
m = "01a"
switch m {
case "01a":
msg_out = "PASS"
}
c <- msg_out
}
我怀疑频道会引入其他隐藏字符
答案 0 :(得分:1)
不清楚您的代码尝试做什么,提供的代码无效。 在所提供的任一示例中,您都没有显示任何尝试从通道读取的内容,两个示例都会打开一个字符串,然后为msg_out(未声明)分配新值并将该值发送到通道。
如果没有完整的代码,就无法分辨出你的错误,这里有一个简单的例子,可以在通道上发送文本并再次读取它。希望这将澄清过程并确认通过通道发送字符串就好了。
如果您仍然无法使其正常运行,我认为您需要发布完整的代码示例才能获得帮助。
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)
}