新手警告。
我可以用字符串键和“任何东西”作为值来制作 map 吗?目标是获得配置数据的映射。此数据可以是单个字符串(或 bool 值或整数,但将其限制为字符串也可以),也可以是字符串数组。示例:我想存储这些项目:
levels = 3
extra-directories = ["foo","bar","baz"]
第一个选项始终是单个值(字符串对我来说没问题)。第二个选项是零个或多个值。
目标是拥有一张 map ,我可以在其中存储这些值,并且在查看 map 时,我可以使用 switch x.(type)
来找出值是什么。
最佳答案
interface{}
是一种接受任何类型的类型。
conf := map[string] interface{} {
"name": "Default",
"server": "localhost",
"timeout": 120,
}
conf["name"]
是一个接口(interface){}
,而不是一个string
,并且conf["timeout"]
是一个 interface{}
而不是 int
。您可以将 conf["name"]
传递给采用 interface{}
的函数,例如 fmt.Println
,但不能将其传递给采用 string
的函数,例如 strings.ToUpper
,除非您知道 interface{}
的值是一个 string
(你这样做)并断言它的类型:
name := conf["name"].(string)
fmt.Println("name:", strings.ToUpper(name))
server := conf["server"].(string)
fmt.Println("server:", strings.ToUpper(server))
timeout := conf["timeout"].(int)
fmt.Println("timeout in minutes:", timeout / 60)
另一种可能适合您的问题的解决方案是定义一个结构:
type Config struct {
Name string
Server string
Timeout int
}
创建配置:
conf := Config{
Name: "Default",
Server: "localhost",
Tiemout: 60,
}
访问配置:
fmt.Println("name:", strings.ToUpper(conf.Name))
fmt.Println("server:", strings.ToUpper(cnf.Server))
fmt.Println("timeout in minutes:", conf.Timeout / 60)
关于string - 使用字符串键和字符串或 slice 值进行映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11801346/