本文介绍了为什么应该返回参数名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
func namedReturn(i int)(ret int)函数返回参数的命名有什么好处? {
ret = i
i + = 2
return
}
func anonReturn(int)int {
ret:= i
i + = 2
return ret
}
解决方案命名它们有一些好处:
- 它用作文档。
- 它们被自动声明并初始化为零值。
- 如果你有多个返回地址,你不需要全部修改它们,因为它改变了函数的返回值只会说return。
还有一些缺点,主要是通过声明相同的变量名称。
Effective Go有一个。
What benefits arise from naming a function's return parameter(s)?
func namedReturn(i int) (ret int) {
ret = i
i += 2
return
}
func anonReturn(i int) int {
ret := i
i += 2
return ret
}
解决方案
There are some benefits to naming them:
- It serves as documentation.
- They are auto-declared and initialized to the zero values.
- If you have multiple return sites, you don't need to change them all if you change the function's return values since it will just say "return".
There are also downsides, mainly that it's easy to accidentally shadow them by declaring a variable of the same name.
Effective Go has a section on named result parameters.
这篇关于为什么应该返回参数名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
08-30 22:59