I have a two-dimensional map that I am trying to write on an output file using Encoding/Gob library but I am getting the following error: “gob: type not registered for interface: map[string]map[int]example1Obj”
This is the code:
This is the code:
gob.Register(map[string]interface{}{})
fileName := os.Args[1]
File, err := os.Create(fileName)
if err != nil {
log.Fatal(err)
}
defer File.Close()
If I were writing production code and wanted to persist the 2 dimensional map values for subsequent reloading I write them as a struct type that could be parsed back into the map when you need to recover it.
Here’s an example. The persister:
package main
import (
"encoding/gob"
"fmt"
"os"
)
func main() {
type Obj1 struct {
Name string
Place string
}
type Dim struct {
X string
Y int
Obj Obj1
}
d := Dim{"", 0, Obj1{"", ""}}
gob.Register(d)
// define a 2 dimensional map
data := map[string]map[int]Obj1{
"x_one": map[int]Obj1{
1: {"obj1", "first"}},
"x_two": map[int]Obj1{
2: {"obj2", "second"}}}
f, err := os.Create("2dimmap.gob")
if err != nil {
fmt.Println("os.Create err:", err)
return
}
defer f.Close()
e := gob.NewEncoder(f)
// for demo; 2 dimensional map values could be persisted
// using gob encoding as they are created/modified. If encoded
// and persisted as map values are inserted/updated; then you'll
// end up with a serialized log file. Then when the 2 dimensional map
// is restored any updates will be processed, as well.
for k, v := range data {
for kk, vv := range v {
d = Dim{k, kk, vv}
}
if err = e.Encode(d); err != nil {
fmt.Println("e.Encode err:", err)
return
}
}
}
Recovering the 2 dimensional map from the backup:
package main
import (
"encoding/gob"
"fmt"
"io"
"os"
)
func main() {
type Obj1 struct {
Name string
Place string
}
type Dim struct {
X string
Y int
Obj Obj1
}
d := Dim{"", 0, Obj1{"", ""}}
gob.Register(d)
f, err := os.Open("2dimmap.gob")
if err != nil {
fmt.Println("os.Open err:", err)
return
}
defer f.Close()
dec := gob.NewDecoder(f)
data := map[string]map[int]Obj1{}
for {
if err := dec.Decode(&d); err != nil {
if err != io.EOF {
fmt.Println("dec.Decode err:", err)
return
}
break
}
y := map[int]Obj1{d.Y: d.Obj}
data[d.X] = y
}
fmt.Printf("%v\n", data)
}