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)
    }
  }