Go 语言是否有函数/方法重载? [英] Does the Go language have function/method overloading?

查看:59
本文介绍了Go 语言是否有函数/方法重载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一个 C 库移植到 Go.C 函数(带有可变参数)定义如下:

I'm porting a C library to Go. A C function (with varargs) is defined like this:

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

所以我创建了包装器 C 函数:

So I created wrapper C functions:

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

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

If I define function in Go like this:

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 是否支持函数(方法)重载,或者这个错误意味着什么?

So does Go support function (method) overloading, or does this error mean something else?

推荐答案

不,它没有.

请参阅 Go 语言常见问题解答,特别是 重载.

如果不需要进行类型匹配,则方法分派会得到简化.使用其他语言的经验告诉我们,拥有多种名称相同但签名不同的方法有时很有用,但在实践中也可能令人困惑和脆弱.仅按名称匹配并要求类型一致是 Go 类型系统中的一个主要简化决策.

Method dispatch is simplified if it doesn't need to do type matching as well. Experience with other languages told us that having a variety of methods with the same name but different signatures was occasionally useful but that it could also be confusing and fragile in practice. Matching only by name and requiring consistency in the types was a major simplifying decision in Go's type system.

更新:2016-04-07

Update: 2016-04-07

虽然 Go 仍然没有重载函数(并且可能永远不会),重载最有用的特性,即调用带有可选参数的函数并为省略的参数推断默认值可以使用可变参数函数来模拟,从那时起已添加.但这是以失去类型检查为代价的.

While Go still does not have overloaded functions (and probably never will), the most useful feature of overloading, that of calling a function with optional arguments and inferring defaults for those omitted can be simulated using a variadic function, which has since been added. But this comes at the loss of type checking.

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

这篇关于Go 语言是否有函数/方法重载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆