首页 > 解决方案 > 如何编写具有不同签名的相同方法的多个实现

问题描述

我有几个相同方法的实现SetRateForMeasure

package repartition

type Repartition interface {
    Name() string
    Compute(meters []models.Meter, totalsProd, totalsConso map[string]float64) []models.Meter
    SetRateForMeasure(meter models.Meter, measure models.Measure, total float64) float64
}

然后,在我的代码中(在 repartition.go 中),我称之为:

rate := repartition.SetRateForMeasure(meter, measure, total)

其中 repartition 是之前定义的接口。

问题是,当我添加此方法的新实现时,我的函数的参数可能会有所不同。

例如,静态重新分区使用仅在这种情况下使用的静态百分比。

我最终添加了参数,以便我对所有方法都有一个通用接口,但结果是有很多未使用的参数,具体取决于实现。

如果我将它添加到公共接口,它将不会用于其他定义。

我试图从我的接口定义中删除这个方法,但现在

rate := repartition.SetRateForMeasure()

不再定义。

我应该如何组织我的代码?

标签: gointerface

解决方案


Go 中没有函数重载,所以你不能用不同的参数声明同一个函数。不过,有几种方法可以实现这一点:

  • 您可以添加具有不同名称和签名的多个函数
  • 您可以更改函数以接受结构而不是参数
SetRateForMeasure(args SetRateOptions) float64

type SetRateOptions struct {
 Meter models.Meter
 Measure models.Measure
 Total float64
 Percentage *float64 // If nil, use default percentage
 ... // more parameters as needed
}

推荐阅读