我是Go编程的新手,我的程序出现问题,该程序使用“switch”语句处理从“map”中检索的值。
该 map 声明如下:
var fields_map map[string]string
稍后按以下方式检索值:
f_code, ok := fields_map["function"]
如果“ok”的值为真,则对检索到的代码进行“切换”,如下所示
switch f_code {
case "meta":
case "users":
case "history":
default:
}
我的问题是,对于每个“case”语句,都会出现如下错误:
f_code上的无效大小写'\u0000'(不符类型的 rune 和字符串)
根据一个网页,我发现“ rune ”定义如下:
Go语言将 rune 一词定义为int32类型的别名
为什么会出现此错误?以及为什么提到“ rune ”?
我的 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
最佳答案
此错误(invalid case '\u0000'
)是seen here,这意味着您尚未为案例值使用实际的双引号:
switch f_code {
case 'meta':
case 'users':
case 'history':
default:
}
如果您将它们替换为
"
,那么它应该起作用,考虑到您的 map (和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>")
}
关于go - 奇怪的错误消息: mismatched types rune and string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59121456/