Go语言是否具有函数/方法重载?


127

我正在将C库移植到Go。AC函数(带有varargs)的定义如下:

curl_easy_setopt(CURL *curl, CURLoption option, ...); 

因此,我创建了包装器C函数:

curl_wrapper_easy_setopt_str(CURL *curl, CURLoption option, char* param);
curl_wrapper_easy_setopt_long(CURL *curl, CURLoption option, long param);

如果我在Go中这样定义函数:

func (e *Easy)SetOption(option Option, param string) {
    e.code = Code(C.curl_wrapper_easy_setopt_str(e.curl, C.CURLoption(option), C.CString(param)))
}

func (e *Easy)SetOption(option Option, param long) {
    e.code = Code(C.curl_wrapper_easy_setopt_long(e.curl, C.CURLoption(option), C.long(param)))
}

Go编译器抱怨:

*Easy·SetOption redeclared in this block

那么Go支持函数(方法)重载了吗,还是这个错误意味着其他?

Answers:


165

不,不是的。

请参阅Go语言常见问题解答,尤其是有关重载的部分。

如果方法分派也不需要进行类型匹配,则可以简化方法分派。其他语言的经验告诉我们,使用具有相同名称但签名不同的多种方法有时会很有用,但在实践中也可能会造成混淆和脆弱。在Go的类型系统中,仅按名称进行匹配并要求类型一致是一个简化的主要决定。

更新时间:2016-04-07

尽管Go仍然没有重载函数(并且可能永远不会重载),但是重载最有用的功能,即调用带有可选参数的函数并为被省略的参数推断默认值,可以使用可变参数函数进行仿真,此函数现已添加。但这带来了类型检查的损失。

例如:http : //changelog.ca/log/2015/01/30/golang



By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.