我是Go编程新手,我的程序有一个问题,它使用"switch“语句来处理从"map”检索到的值。
该映射声明如下:
var fields_map map[string]string稍后将按如下方式检索值:
f_code, ok := fields_map["function"]如果"ok“的值为true,那么我将对检索到的代码执行"switch”操作,如下所示
switch f_code {
case "meta":
case "users":
case "history":
default:
}我的问题是,对于每个" case“语句,我都会收到如下错误: switch on f_code中的case '\u0000‘无效(类型rune和string不匹配)
根据我发现的一个网页," rune“的定义如下: Go语言将单词rune定义为int32类型的别名
为什么我会得到这个错误?为什么提到“符文”?我的map的键和值都被声明为"string“,所以我很困惑。
有什么想法吗?
我创建了一个精简版本的代码,它具有相同的编译错误
1 package main
2
3 import (
4 "fmt"
5 )
6
7 var fields_count int
8 var fields_map map[string]string
9
10 func parse_fields() {
11 fields_count = 0
12 fields_map = make(map[string]string) // initialize the map
13
14 } // parse_fields
15
16 func main() {
17
18 parse_fields()
19 f_code, ok := fields_map["function"] // test for existance of function code
20 if ok {
21 switch f_code {
22 case 'meta':
23 break;
24 case 'users':
25 break;
26 case 'history':
27 break;
28 default:
29 break;
30 }// switch
31 } else {
32 fmt.Println("<H3>No function code detected</H3>")
33 }
34
35 } // main发布于 2019-12-01 08:32:44
此错误(invalid case '\u0000')为seen here,这意味着您的案例值没有使用实际的双引号:
switch f_code {
case 'meta':
case 'users':
case 'history':
default:
}如果你用"替换它们,考虑到你的地图(和f_code)使用字符串,它应该可以工作。
OP的示例是用this playground编写的,并且确实会生成illegal rune literal错误。
使用双引号不会产生错误,就像在this playground中一样。
parse_fields()
f_code, ok := fields_map["function"] // test for existance of function code
if ok {
switch f_code {
case "meta":
break
case "users":
break
case "history":
break
default:
break
} // switch
} else {
fmt.Println("<H3>No function code detected</H3>")
}发布于 2019-12-01 12:22:36
反射包用于获取值的类型,您也可以根据类型进行切换。
package main
import (
"fmt"
"reflect"
)
func main() {
myMap := map[string]string{ "test1":"testing", "test2":"testing2" }
value, ok := myMap["test1"]
fmt.Println(reflect.TypeOf(value), value)
if (ok) {
switch value {
case "debug1":
fmt.Println("not what i meant")
case "testing":
fmt.Println("This is what i am looking for")
default:
fmt.Println("default value ")
}
}
}输出:
字符串测试
这就是我要找的
https://stackoverflow.com/questions/59121456
复制相似问题