0

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
}```
2
  • 1
    If you get an error that's relevant to your question, please be sure to include it - verbatim - in the question. Commented Oct 23, 2021 at 1:13
  • What do you mean, it returns "an array of either all Person1 or all Person2"? A function in Go cannot return one of two types. Show the signature of handler.PersonRequest Commented Oct 23, 2021 at 1:33

1 Answer 1

2

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)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.