映射与字符串键和字符串或切片值?
Newbee warning.
Can I make a map with a string key and "anything" as a value? The goal is to have a map of configuration data. This data can be either a single string (or boolean value or integer, but restricting this to a string is fine), or it can be an array of strings. Example: I'd like to store these items:
levels = 3
extra-directories = ["foo","bar","baz"]
The first option is always a single value (a string would be OK for me). The second option is zero or more values.
The goal is to have a single map where I can store these values and when looking at the map, I could use switch x.(type)
to find out what the value is.
Newbee警告。 p>
我可以使用字符串键制作地图吗? “什么”作为价值? 目标是拥有配置数据图。 该数据可以是单个字符串(或布尔值或整数,但是将其限制为字符串是可以的),也可以是字符串数组。 示例:我想存储以下项目: p>
levels = 3
extra-directories = [“ foo”,“ bar”,“ baz”]
code> pre>
第一个选项始终是单个值(字符串对我来说是可以的)。 第二个选项是零个或多个值。 p>
目标是制作一张可以存储这些值的地图,当查看地图时,可以使用 switch x。(type) code>查找 找出值是什么。 p>
div>
interface{}
is a type that accepts any type.
conf := map[string] interface{} {
"name": "Default",
"server": "localhost",
"timeout": 120,
}
conf["name"]
is an interface{}
not a string
, and conf["timeout"]
is an interface{}
not an int
. You can pass conf["name"]
to functions that take interface{}
like fmt.Println
, but you can't pass it to functions that take string
like strings.ToUpper
, unless you know that the interface{}
's value is a string
(which you do) and assert it's type:
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)
Another solution that might fit your problem is to define a struct:
type Config struct {
Name string
Server string
Timeout int
}
Create configuration:
conf := Config{
Name: "Default",
Server: "localhost",
Tiemout: 60,
}
Access configuration:
fmt.Println("name:", strings.ToUpper(conf.Name))
fmt.Println("server:", strings.ToUpper(cnf.Server))
fmt.Println("timeout in minutes:", conf.Timeout / 60)
Yes, you can do that using a map having type map[string]interface{}
.