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 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大