duandaoji3992 2012-08-03 18:32
浏览 63
已采纳

映射与字符串键和字符串或切片值?

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.

  • 写回答

2条回答 默认 最新

  • dpt62283 2012-08-03 19:44
    关注

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记