fab*_*ous 1 overloading function go
我有一个当前没有收到bool参数的函数,但随后用硬编码的bool调用另一个函数.我们需要删除硬编码调用并允许传递bool.
我首先想到我可以尝试一些默认参数 - 我的谷歌搜索导致Go显然不支持可选(resp.default)参数.
所以我想我会尝试函数重载.
我在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)
}
Run Code Online (Sandbox Code Playgroud)
当我运行我的测试时,我得到(原谅我省略了部分真正的文件路径):
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
Run Code Online (Sandbox Code Playgroud)
Go中没有重载.不是编写具有不同功能的相同名称的函数,而是更好地表达函数在函数名称中的作用.在这种情况下,通常会做的是这样的事情:
func (self *RemoteSystem) Apply(rpath, lpath string, dynamic bool) error {
result, err := anotherFunc(rpath, dynamic)
}
func (self *RemoteSystem) ApplyDynamic(rpath, lpath string ) error {
//in this function anotherFunc was being called, and dynamic is hardcoded to true
return self.Apply(rpath, lpath, true)
}
Run Code Online (Sandbox Code Playgroud)
只需通过功能名称,您就可以轻松分辨出不同之处和原因.
提供一些上下文(双关语)的另一个例子.我使用go-endpoints在Go中编写了很多Google App Engine代码.记录事物的方式因您是否有不同而有所不同context.我的日志记录功能就像这样结束了.
func LogViaContext(c context.Context, m string, v ...interface{}) {
if c != nil {
appenginelog.Debugf(c, m, v...)
}
}
func LogViaRequest(r *http.Request, m string, v ...interface{}) {
if r != nil {
c := appengine.NewContext(r)
LogViaContext(c, m, v...)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
576 次 |
| 最近记录: |