Home > other >  Golang generic return type on a method
Golang generic return type on a method

Time:08-05

I'm new to golang, and I'm struggling to see how I can get some generic behavior on a method.


func (s *service) getCars(filter Filter) ([]car, error){
    var err error
    var cars []car
    switch filter {
    case filter.Toyota:
        cars, err = s.dbClient.getToyotas()
    case filter.Honda:
        cars, err = s.dbClient.getHondas()
    }
    return cars, nil
}

The objects returned from s.dbClient.getToyotas() and s.dbClient.getHondas() are data structs with the same fields, but have different types. I should note these returned structs are auto generated, so I don't have the ability to alter them.

It looks like go interfaces only allow methods, and not data fields, so I don't if it's even possible to define a car type that can be used as the return type. I looked at generics as well, but it seems that generics are not allowed on struct methods.

What's the idiomatic way of doing something like this in go?

CodePudding user response:

Defining a common interface is the idiomatic way to go.

Access to fields can be "modeled" by defining accessor methods on interface and then implementing those on specific structs.

In fact, it is a better solution as those methods can do more than simple access to internal, private variables. For example, they can have lazy initialization or cached access built in. Each struct can have unique implementation or you can have a base struct with default one.

  •  Tags:  
  • go
  • Related