【发布时间】:2017-08-16 14:24:57
【问题描述】:
我有一个函数当前没有接收到 bool 参数,但随后调用了另一个带有硬编码 bool 的函数。我们需要删除硬编码调用并允许传递一个布尔值。
我首先认为我可以尝试一些默认参数 - 我的谷歌搜索结果显示 Go 显然不支持可选(或默认)参数。
所以我想我会尝试函数重载。
我在 reddit 上找到了这个帖子,上面说它适用于自版本 1.7.3 以来的特殊指令:
https://www.reddit.com/r/golang/comments/5c57kg/when_did_function_overloading_get_slipped_in/
我正在使用1.8,但仍然无法正常工作。
我什至不确定我是否可以使用该指令,但我推测立即更改函数签名可能很危险,因为我不知道谁使用该函数...
无论如何 - 即使 //+ 重载它也不起作用
在 Go 中是否有任何“特殊”的方式或模式来解决这个问题?
//some comment
//+overloaded
func (self *RemoteSystem) Apply(rpath, lpath string, dynamic bool) error {
result, err := anotherFunc(rpath, dynamic)
}
//some comment
//+overloaded
func (self *RemoteSystem) Apply(rpath, lpath string ) error {
//in this function anotherFunc was being called, and dynamic is hardcoded to true
//result, err := anotherFunc(rpath, true)
return self.Apply(rpath, lpath, true)
}
当我运行测试时,我得到(请原谅我省略了部分文件的真实路径):
too many arguments in call to self.Apply
have (string, string, bool)
want (string, string)
../remotesystem.go:178: (*RemoteSystem).Apply redeclared in this block
previous declaration at ../remotesystem.go:185
【问题讨论】:
-
Go 没有函数或方法重载。
-
还要检查引用的reddit主题中的第一条评论
-
好的,那么除了改变函数签名没有别的办法了吗?
-
Does the Go language have function/method overloading? 的可能重复项可能的解决方案/替代方案:Optional Parameters?
标签: function go overloading