2017-08-19 33 views
0

通过传递参数m,从goroutine调用此函数。在Switch语句中无法识别来自通道的字符串变量golang

以米发送的值是字符串:“01A”,并声明开关不承认

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 
} 

我怀疑通道将引入其他隐藏字符

回答

1

目前还不清楚您的代码正在尝试执行哪些操作,所提供的代码无效。 在提供的任何示例中,您都没有显示任何尝试从通道读取数据的情况,这两个示例都打开一个字符串,然后为msg_out(未声明)分配一个新值,并将该值发送到通道。

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

如果你仍然不能得到它的工作,我认为你需要发布完整的代码示例来获得帮助。

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