interface{}是一种接受任何类型的类型。
conf := map[string] interface{} {
"name": "Default",
"server": "localhost",
"timeout": 120,
}
conf["name"]是一个interface{}非一个string,并且conf["timeout"]是一个interface{}非一个int。您可以将其传递conf["name"]给采用interface{}like的函数fmt.Println,但不能将其传递给采用stringlike的函数strings.ToUpper,除非您知道interface{}' 的值是 a 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)