0

I am trying to copy a map to another map so i used gob in order to do this. But when i unmarshal a json to map[string]interface{} and then try to copy it to another map i get an error in the encoding part.

This is the code:

 package main import ( "encoding/gob" "bytes" "fmt" "encoding/json" ) func CopyMapToAnotherMap(req map[string]interface{}) (cpy map[string]interface{}, err error) { var mod bytes.Buffer gob.Register(map[string]interface{}{}) enc := gob.NewEncoder(&mod) dec := gob.NewDecoder(&mod) err = enc.Encode(req) if err != nil { fmt.Println("Unable to encode map", err) return nil, err } err = dec.Decode(&cpy) if err != nil { fmt.Println("Unable to decode map", err) return nil, err } return cpy, nil } func main() { my := `{"data":[{"aa":1},{"bb":2}]}` var m map[string]interface{} err := json.Unmarshal([]byte(my), &m) if err != nil { fmt.Println(err) } CopyMapToAnotherMap(m) } 

and i am getting an error : gob: type not registered for interface: []interface {}

How can this be avoided?

6
  • 1
    Do not use gob for such things. Commented May 22, 2018 at 8:20
  • the error includes []interface {} but not map[string]interface {}. Are you sure the error message is correct? If so, then it looks it is coming from something else. Commented May 22, 2018 at 8:58
  • @Volker. Can you be more specific? What is the right way on your opinion. I have the similar problem and use marshalling for this but internet is full of advices to use gob and benchmarks showing that gob is much faster and works. Commented May 23, 2018 at 6:21
  • Copying one map to an other map is done by iterating over the source like for k,v := range src and populating the destination like dst[k] = v. If your input and output types do not coincident then you have to convert the keys and values. This is called programming. The internet is not full of recommendations to use gob because gob is something very useful but also very specific. Stop looking for a "magic" solution. Think about what you want to do exactly and start writing code. Commented May 23, 2018 at 7:39
  • 1
    @Volker You are right in general, but if your map has dynamic structure and hundreds of rows, you start dreaming about some magic rather than writing thousands rows of code with endless if/else, casts and type assertions.This part of programming (and yes, I've heard about such a word) is less exciting. So I just wanted to be sure that there is no magic I'm not aware of. Thanks anyway. Commented May 23, 2018 at 7:56

1 Answer 1

1

Fix by registering the type at program initialization time:

func init() { gob.Register([]interface{}(nil)) } 

Run an example on the playground.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.