Golang:为什么捕获某些函数的返回值是可选的?

huangapple go评论72阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2016年11月30日 03:48:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/40874559.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定