gogo-map

How can I make a map of parent structs in go?


I'm coming from Java/Kotlin so I'm a bit new to the composition-over-inheritance world that Go is in :)

So in Java, I could make a

abstract class Pet

and a subclass

class Dog extends Pet
class Cat extends Pet

and then make a

Map<String, Pet> mapOfPets = HashMap();
mapOfPets.put("puppy",  new Dog());
mapOfPets.put("kitty",  new Cat());

From here, I'm trying to do the equivalent in Golang. Here's how my attempt is going

struct Pet{
 // ...
}
struct Dog{
  Pet
}
struct Cat{
  Pet
}
func () {
  petMap := make(map[string]*Pet)

  //invalid
  petMap["puppy"] = &Dog{ ... } 
  petMap["kitty"] = &Cat{ ... }

  // valid
  puppy2 := &Dog{ ... }
  kitty2 := &Cat{ ... }
  petMap["puppy2"] = &puppy2.Pet
  petMap["kitty2"] = &kitty2.Pet
}()

I know the valid portion of the code should work, but I'm losing the content within the Dog and Cat class. How should I model the map and/or structs for me to be able to make something similar to the invalid portion of the code?

It'd be annoying creating a map for each of the 'subclasses' (which I know is the incorrect term here)

PS: any articles or guides on how I should be doing composition would be greatly appreciated too!

Thank you!


Solution

  • You should be using interfaces for this. Your map would be map[string]Pet, where Pet is:

    type Pet interface {
      // methods an implementer of Pet should have
    }
    

    Then your concrete types (Dog etc.) would implement the Pet interface by having the right methods.

    For more information on interfaces, see the Tour of Go, gobyexample etc. Interfaces will be described extensively in any introductory guide to Go.