gpt4 book ai didi

go - Go语言有函数/方法重载吗?

转载 作者:数据小太阳 更新时间:2023-10-29 03:27:52 24 4
gpt4 key购买 nike

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

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是支持函数(方法)重载,还是这个错误有别的意思?

最佳答案

不,它没有。

参见 Go Language FAQ ,特别是关于 overloading 的部分.

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

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

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

关于go - Go语言有函数/方法重载吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34691442/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com