命名函数的返回参数有什么好处?
func namedReturn(i int) (ret int) {
ret = i
i += 2
return
}
func anonReturn(i int) int {
ret := i
i += 2
return ret
}
最佳答案
命名它们有一些好处:
- 它用作文档。
- 它们会自动声明并初始化为零值。
- 如果您有多个返回站点,则在更改函数的返回值时无需全部更改,因为它只会说“返回”。
也有缺点,主要是通过声明同名变量很容易意外地隐藏它们。
Effective Go 有一个 section on named result parameters :
The return or result "parameters" of a Go function can be given names and used as regular variables, just like the incoming parameters. When named, they are initialized to the zero values for their types when the function begins; if the function executes a return statement with no arguments, the current values of the result parameters are used as the returned values.
The names are not mandatory but they can make code shorter and clearer: they're documentation. If we name the results of nextInt it becomes obvious which returned int is which.
func nextInt(b []byte, pos int) (value, nextPos int) {
[...]
关于go - 为什么要命名返回参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15089726/