go – Which is the most effective way to convert an interface pointer slice to struct pointer slice?-ThrowExceptions

Exception or error:

The basic problem is that I got an []*interface{} and I need to convert it to []*MyStruct.

I’m trying something like that, but it’s not so fast. In my case, in the example code, the lines slice contains maps, so hard cast didn’t work.

var lines []*interface{}
var results []*MyStruct
for _, s := range lines {
  if s != nil {
    someJson, err := json.Marshal(s)
    if err != nil {
    v := MyStruct{}
    if err := json.Unmarshal(someJson, &v); err != nil {
    results = append(results, &v)
How to solve:

If you have to use json, the only optimization I see is to pre-allocate your results so that append doesn’t have to do it on “every call” (unlikely, implementation dependent but more often than once)

results := make([]*MyStruct, 0, len(lines))

Leave a Reply

Your email address will not be published. Required fields are marked *