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
}```
handler.PersonRequest