3

I wants to assign a map to an interface where underlying value is of type map[string]interface.

type Data struct{
  data interface{}
}

result := make(map[string]interface{})
data := Data{
   data:result
}

details := make(map[string]interface{})
details["CreatedFor"] = "dfasfasdf"
details["OwnedBy"] = "fasfsad"

How can I insert details value to data interface inside Data struct ?

0

1 Answer 1

3

To be able to treat an interface as a map, you need to type check it as a map first.

I've modified your sample code a bit to make it clearer, with inline comments explaining what it does:

package main

import "fmt"

func main() {
    // Data struct containing an interface field.
    type Data struct {
        internal interface{}
    }

    // Assign a map to the field.
    type myMap map[string]interface{}
    data := Data{
        internal: make(myMap),
    }

    // Now, we want to access the field again, but as a map:
    // check that it matches the type we want.
    internalMap, ok := data.internal.(myMap)
    if !ok {
        panic("data.internal is not a map")
    }

    // Now what we have the correct type, we can treat it as a map.
    internalMap["CreatedFor"] = "dfasfasdf"
    internalMap["OwnedBy"] = "fasfsad"

    // Print the overall struct.
    fmt.Println(data)
}

This outputs:

{map[CreatedFor:dfasfasdf OwnedBy:fasfsad]}
Sign up to request clarification or add additional context in comments.

1 Comment

That was exactly I am asking only thing is that I wants to extract the underlying value of interface which I did using type assertion

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.