go - 如何编写具有不同签名的相同方法的多个实现
问题描述
我有几个相同方法的实现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()
不再定义。
我应该如何组织我的代码?
解决方案
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
}
推荐阅读
- visual-studio - Visual Studio 中缺少 macOS 模板
- c# - 我有一张收据表格,我需要将此表格 tex 框链接到其他表格中的其他文本框,我该怎么做?
- sql - 如何在动态 SQL 中包含中断?
- java - 如何在 Secure_CRT 上远程编辑 zip 内的文件?
- java - 使用超类的变量访问派生类的对象
- angular - 从服务器获取数据后,角度材料表排序不起作用
- dart - 在 vscode 中无法启动 Dart Analyzer
- java - 如何使用 Java 公开 WSS 的“安全 websocket”
- sql-server - 当我将代码粘贴到 ssis 时,Concat 函数需要两个参数
- react-native - 如何将整个应用程序包装在标签中?