【问题标题】:Overloading a function in go doesn't work在 go 中重载函数不起作用
【发布时间】: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

【问题讨论】:

标签: function go overloading


【解决方案1】:

重载在 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)
}

只需通过函数名称,您就可以轻松分辨出不同之处和原因。

提供一些上下文的另一个示例(双关语)。 我使用 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...)
    }
}

【讨论】:

    【解决方案2】:

    来自Reddit post

    统一码。我可以通过像素来判断。

    Go 不支持函数重载。但它确实支持在函数名中使用 Unicode 字符,这样您就可以编写看起来像其他函数名的函数名。

    第一个是setValue,第二个是setV\u0430lue aka setV\xd0\xb0lue(带有CYRILLIC SMALL LETTER A),第三个是setVal\U0001d69ee aka setVal\xf0\x9d\x9a\x9ee(带有MATHEMATICAL MONOSPACE SMALL U)。

    另见:

    【讨论】:

    • 好的,谢谢。看起来不是解决问题的好方法,但我确实学到了一些东西。第一次阅读reddit链接时我不明白。
    • 不,这根本不是什么好东西。原来的帖子是个玩笑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-28
    • 2014-01-12
    • 1970-01-01
    • 1970-01-01
    • 2012-04-29
    • 1970-01-01
    • 2013-11-27
    相关资源
    最近更新 更多