0

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?

abrarisme
  • 495
  • 1
  • 6
  • 14
  • 2
    Why are you renaming types from other packages within your package? That's usually not something you want to do. – JimB Jun 21 '17 at 12:38
  • I want to add additional methods to those types, and it seems that I can either use aliases or embedding. The alias within my package will not be exported. – abrarisme Jun 21 '17 at 12:47
  • 4
    Type "aliases" don't exist yet (coming in go1.9), and renaming a type creates an entirely new type with a new method set. You almost always want to use embedding to add to the method set. – JimB Jun 21 '17 at 12:50
  • Yup in this case I do want a new type with a new method set. I saw this page earlier: https://stackoverflow.com/questions/28800672/how-to-add-new-methods-to-an-existing-type-in-go . But I think I'm seeing that what I want to do isn't possible because of the static typing of Go (using reflect to convert interface to struct) – abrarisme Jun 21 '17 at 13:06
  • 1
    I have to agree that there is some design flaw here, but I can't say what specifically without more context. It seems like you may have painted yourself into a corner architecturally. This looks like a potential [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – Adrian Jun 21 '17 at 13:23

0 Answers0