I am trying to create a generic function that can accept a key string and a reference to an object.
The function reads a key's content, which is a serialized byte array out of an original object of the same type and it should assign that (deserializing) to an empty structure of that same type. The function wants to be generic, so it can serialize a type A as well as B or []C
Here is what I tried to do:
func GetObject(key string, thing interface{}) error {
var buf bytes.Buffer
dec := gob.NewDecoder(&buf)
err := dec.Decode(thing)
if err != nil {
log.Errorf(cs.ctx, "cloud store - GetObject - decode error:", err)
return err
}
return nil
}
This is how I try to invoke the above function:
newThing := MyStruct{}
err := GetObject("a123", &newThing)
The last lines about cause a runtime error:
decode error:%!(EXTRA *errors.errorString=EOF)
the question:
- is the interface approach correct for this purpose (allow the function be used generically) ?
- The serialization error ( using Gob ) seems to be problematic. Any suggestions on how to rectify that ?