user3550166
user3550166

Reputation: 129

Retrieving values from nested map in 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].

Upvotes: 1

Views: 3090

Answers (1)

Girdhar Sojitra
Girdhar Sojitra

Reputation: 678

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)
    }
}

Upvotes: 1

Related Questions