doutu1939 2017-04-12 00:07
浏览 24

从Golang的嵌套地图中检索值

I'm trying to retrieving a value from a map within a map. I have followed online tutorials but not getting the right answer. This is my program:

type OptionMap map[string]interface{}
func(options OptionMap) {
    opt, _ := options["data2"].(OptionMap)
    fmt.Println("opt", opt)
    for key, value := range options {
        fmt.Println("Key:", key, "Value:", value)
    }
}

options has two keys data1 and data2 . Inside for loop the printf prints following

Key: data1 Value: false
Key: data2 Value: map[h:5]

When I run the code

opt, _ := options["data2"].(OptionMap)

I'm getting nil in opt. I'm not sure how to retrieve value of map[h:5].

  • 写回答

1条回答 默认 最新

  • duanjianqu3685 2017-04-12 05:56
    关注

    You are getting nil value for inner map because you have not created inner map using type OptionMap.You must have created it using map[string]interface{} and trying to assert to OptionMap which is failing in getting nil value. See below example which is working with OptionMap type,too.Go through type assertion page at https://tour.golang.org/methods/15

    package main
    
    import "fmt"
    
    
    
    type OptionMap map[string]interface{}
    
    func main()  {
        opt := make(OptionMap)
        ineeropt := make(OptionMap)     // while creating Map specify OptionMap type
        ineeropt["h"]=5
        opt["data1"] = false
        opt["data2"] = ineeropt
        test(opt)
    
    
    }
    func test(options OptionMap) {
        opt, _ := options["data2"].(OptionMap)  //If inner map is created using OptionMap then opt won't be nil
        fmt.Println("opt", opt)
        fmt.Println("opt", options)
        for key, value := range options {
            fmt.Println("Key:", key, "Value:", value)
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)