vendredi 5 juillet 2019

Is there a way to dynamically add cases to a golang type switch?

I have a simple type switch that I need to perform operations according to the type it receives. But I want to add methods to be run according to a certain type dynamically.

I have this method called "Register", in which I register a function to be executed for a certain reflect.Type T. These transformations will be stored in a map whose key is the actual type.

/*Register ...*/
func (bs *BaseStreamer) Register(
    transform func (in interface{}) interface{},
    T reflect.Type) {

        _, ok := bs.transformations[T]
        if ok {
            log.Printf(
               "Warning: Overriding method for type %s",
               T.String()
            )
        }
        bs.transformations[T] = transform
}

Now I want to iterate over this map and dynamically add cases to my TypeSwitch, so the right method will be executed for its respective type, and I don't know if this is even possible in go. I tried looking for it in the reflect package, but the only option there seems to do something similar to the select operation. Well, as I'm not dealing with channels here, I really only needed to add cases dynamically to my switch.

switch item := newItem.(type) {

   // Here I'd like to iterate over my map
   // and add cases for each pair key, value
   // (type, function) i have on my map

   default:
      log.Printf("No transformation function registered for any of the types")
}

Is this even possible in go? Is there something similar to SelectCase from the reflect package?





Aucun commentaire:

Enregistrer un commentaire