Ernestas Poškus

Technical blog

"We must view with profound respect the infinite capacity of the human mind to resist the introduction of useful knowledge." - Thomas R. Lounsbury

| github | linkedin | twitter |

ansible 2 / elasticsearch 2 / kernel 1 / learning 27 / linux 2 / mnemonics 1 / nginx 1 / paper 27 / personal 5 / research 26 / review 27 / rust 1 / scientific 27 / tools 2 /

Golang dynamic struct decoration

WC 96 / RT 1min


Dynamic struct decoration using type assertion.

Use cases: API / templates.

Having simple map of:

  input :=  map[string]interface{}{
    "Key1": []string{"some", "key"},
    "key3": nil,
    "val": 2,
    "val2": "str",
    "val3": 4,
  }

One can decorate it using type assertion by iterating over it.

  for key, value := range input {
    slice, ok := value.([]string)
    if ok {
      input["Count"+key] = len(slice)
    }
  }

This becomes very useful when serializing struct into json. To serialize struct use github.com/fatih/structs

  input := structs.Map(...)

  for key, value := range input {
    slice, ok := value.([]string)
    if ok {
      input["Count"+key] = len(slice)
    }
  }