vendredi 8 juin 2018

common function to create map[string]struct from slice of struct dynamically

I have two different struct as mentioned below A abd B and two process functions. Is there any way by means of which i can write a common function to generate the map[string]struct for the both the struct. Moreover, is there any way using reflection given the struct name i can create the object of the same?

type A struct {
    name string
    // more fields
}


type B struct {
    name string
    // more fields  
}

func ProcessA(input []A) map[string]A {
    output := make(map[string]A)
    for _, v := range input {
         output[v.name] = v
    }
  return output
}


func ProcessB(input []B) map[string]B {
    output := make(map[string]B)
    for _, v := range input {
         output[v.name] = v
    }
  return output
}





Aucun commentaire:

Enregistrer un commentaire