I want to convert some struct types between different packages and then operate on the structs that are in my package without using if/else
or switch
statements. Is that possible to do using just maps
and interfaces
? I have some ideas in place for how I can do this.
Package Other
type Update interface{}
type FirstUpdate struct {
x int
y int
}
type SecondUpdate struct {
z string
}
// these methods return different implementations of Update structs
FirstRequestConverter(events []string, topic string) Update
SecondRequestConverter(events []string, topic string) Update
Package Mine
type ConversionFunction func([]string, string) other.Update
type FirstUpdateConverted other.FirstUpdate
type SecondUpdateConverted other.SecondUpdate
type ServiceCaller interface {
// includes relevant methods
}
topicsMap := map[string]ConversionFunction{
"first_topic": other.FirstRequestConverter,
"second_topic": other.SecondRequestConverter,
}
conversionFunction = topicsMap[topic]
// need to convert other package types to alias types
...
updateConverted.callService()
Here, my map from string
to ConversionFunction
lets me pick the conversion function I want to use at runtime. And if both FirstUpdateConverted
and SecondUpdateConverted
implement the ServiceCaller
interface, I can choose how the converted structure is handled at runtime too.
In order to convert from FirstUpdate
to FirstUpdateConverted
(or any of the other alias types), however, I need to use a switch
and convert manually.
Is there another way to do the struct conversion step?