1

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].

8
  • 1
    Please show us the code how you construct the nested map. Commented Apr 12, 2017 at 0:22
  • I'm not constructing it. This map is constructed by docker. BTW im getting the right value map[h:5] but I'm not sure how to retrieve the value of inner map. Commented Apr 12, 2017 at 0:28
  • Please get in the habit of using gofmt. It will make your code easier for you, and others to read. Commented Apr 12, 2017 at 0:46
  • When I print options => map[data1:false data2:map[h:5]] Commented Apr 12, 2017 at 0:46
  • Please include the complete code, including where you build your nested map. I can't really tell what you're trying to do. What does map[h:5] mean? Commented Apr 12, 2017 at 0:47

1 Answer 1

1

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)
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.