为什么命名函数的返回参数?
自动declaration and Initialization
:命名的返回参数自动声明并在函数调用后将其初始化为零值。这消除了功能正文内的显式变量声明的需求。
:使用命名返回参数,可以在返回参数的当前值时省略“返回”关键字。 This simplifies the function code and reduces the likelihood of introducing errors in multiple return paths.
Example:
Consider the following two Go functions:- func namedReturn(i int) (ret int) {
ret = i
i = 2
返回
}
func anontreturn(i int)int {
ret:= i
i = 2
返回ret
}
考虑:- 尽管存在这个潜在的问题,但命名返回参数仍然是一个有价值的实践。有效GO强调了其用于文档和代码简化的实用程序。