英文:
Golang: Why Is Catching Certain Function Return Values Optional?
问题
为什么Go语言有时允许调用函数时不捕获所有返回值?例如:
func TestGolang() {
myMap := make(map[string]string)
test := myMap["value"]
// 或者
test, success := myMap["value"]
}
而在其他时候,你必须捕获所有的返回结果,如果你不想使用这个值,可以使用空标识符"_"。例如:
test := os.Stat("test") // 报错
test, _ := os.Stat("test") // 唯一的解决方法
我原以为Go语言不支持单个函数的不同方法签名。第一个例子是如何工作的?我能否实现自己的函数,可选地返回错误或状态标志,但如果不捕获第二个返回值,不会出错呢?
英文:
Why does go sometimes allow you to call functions without catching both return values? Such as:
func TestGolang() {
myMap := make(map[string]string)
test := myMap["value"]
// or
test, success := myMap["value"]
}
While at other times, you are required to catch all the return results and use a blank identifier if you do not want to use the value?
test := os.Stat("test") // fails
test, _ := os.Stat("test") // only way to make it work
I thought golang does not support different method signatures for a single function. How does the first example work? Can I implement my own functions that optionally return an error or a status flag but does not error out if the 2nd return value is not caught?
答案1
得分: 7
实际上,Go语言不支持函数重载,因此无法为函数定义不同的签名。但是,语言定义中的某些操作(例如通道接收器或从映射中获取数据)具有类似于重载的行为。
英文:
In fact, golang doesn't support function overloading, so you can't define different signatures for a function. But some operations from the language definition (like the channel receiver or obtaining data from a map) are 'blessed' with overloading-like behavior.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论