Ernestas Poškus

Technical blog

| github | linkedin | twitter |

ansible 2 / kernel 1 / learning 26 / linux 2 / nginx 1 / paper 26 / personal 2 / research 25 / review 26 / rust 1 / scientific 26 / 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)
    }
  }