Golang方法的通用返回类型

huangapple go评论73阅读模式
英文:

Golang generic return type on a method

问题

我是你的中文翻译助手,以下是翻译好的内容:

我对golang还不熟悉,我在努力弄清楚如何在方法上实现一些通用行为。


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
}

从s.dbClient.getToyotas()和s.dbClient.getHondas()返回的对象是具有相同字段但类型不同的数据结构。我应该注意到这些返回的结构体是自动生成的,所以我无法修改它们。

看起来go接口只允许方法,而不是数据字段,所以我不知道是否可以定义一个作为返回类型的car类型。我也看了泛型,但似乎在结构体方法上不允许使用泛型。

在go中,如何以惯用的方式实现这样的功能?

英文:

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?

答案1

得分: 2

定义一个通用接口是一种惯用的方法。

通过在接口上定义访问器方法,可以对字段进行“建模”,然后在特定的结构体上实现这些方法。

实际上,这是一个更好的解决方案,因为这些方法可以做更多的事情,而不仅仅是简单地访问内部的私有变量。例如,它们可以具有延迟初始化或缓存访问的功能。每个结构体可以有独特的实现,或者你可以有一个带有默认实现的基础结构体。

英文:

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.

huangapple
  • 本文由 发表于 2022年8月3日 07:28:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/73214777.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定