mardi 10 janvier 2023

what's the most efficient way to iterate over an interface{} object in Go?

e.g. Assuming the interface{} object is a struct {"a":1, "b": "test", c: &AnotherStruct{}}, and we need to iterate the object to get value of each field "a", "b", "c".

I can think of two ways:

  1. use Go reflection directly.
  2. use json.Marshal()/json.Unmarshal() to convert the object to map[string]interface{}, and then iterate over the map to do type assertions, this also calls reflection, however there might be some json library having optimizations inside which might gain better performance, e.g. https://github.com/bytedance/sonic.

I was wondering which one is more efficient and is there any other way to do it?





Aucun commentaire:

Enregistrer un commentaire