nathan.hunt
nathan.hunt

Reputation: 127

Go lang - Polymorphism for interface; array of types which implement interface

I'm coming from a Java background, so I'm pretty lost by Go's approach to OOP. I'm trying to write a logging function that, fundamentally, can accept an array of either one type or another. To clarify: the arrays will not mix type, they will be an array of all either Type1 or Type 2.

I created an interface for both these types to implement, but my IDE said it can't use the type as the interface. What's the better, more Go-like approach here?

type Loggable interface {
  GetFirstName() string
  GetLastName() string
}

type Person1 struct {
  FirstName string
  LastName string
}

func (t Person1) GetFirstName() string {
  return t.FirstName
}

func (t Person1) GetLastName() string {
  return t.LastName
}

type Person2 struct {
  FirstName2 string
  LastName2 string
}

func (t Person2) GetFirstName() string {
  return t.FirstName2
}

func (t Person2) GetLastName() string {
  return t.LastName2
}

func performLogging(logger LoggingPackage.Logger, loggingList []Loggable){
  for _, person := range loggingList {
    logger.Logf("Person is %s %s", person.GetFirstName(), person.GetLastName())
  }
}

func relevantFunction() {
  personList := handler.PersonRequest() // returns an array of all either Person1, or all Person2
  performLogging(logger, personList) // can't use []Person1 or []Person2 as []Loggable
}```

Upvotes: 0

Views: 333

Answers (1)

Zombo
Zombo

Reputation: 1

I find it helps in these cases to rip out all code that is not central to the problem. This example works as expected:

package main
import "fmt"

type Loggable interface {
   GetFirstName() string
}

type Person1 struct { FirstName string }
func (t Person1) GetFirstName() string { return t.FirstName }

type Person2 struct { FirstName2 string }
func (t Person2) GetFirstName() string { return t.FirstName2 }

func performLogging(loggingList []Loggable){
   for _, person := range loggingList {
      fmt.Println(person.GetFirstName())
   }
}

func main() {
   people := []Loggable{
      Person1{"Angela"}, Person2{"Tyrell"},
   }
   performLogging(people)
}

Upvotes: 2

Related Questions