3

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?

  • Are you asking how to call one of the registered functions given a value of one of the registered types? It will be helpful if can give some examples of what switch would look like if written statically. Part one of the question works with *functions*. Part two talks about executing a *method* for a type. What are these methods? – Charlie Tumahai Jul 06 '19 at 01:39
  • Your Register function is invalid go. But if I understand, why would you use a switch? Just do a map lookup. – Jonathan Hall Jul 06 '19 at 07:55

0 Answers0