api 返回参数 命名
In Go you can write functions that have named result parameters.
在Go中,您可以编写具有命名结果参数的函数。
Two examples from the spec:
规范中的两个示例:
func complexF3() (re float64, im float64) {
re = 7.0
im = 4.0
return
}
func (devnull) Write(p []byte) (n int, _ error) {
n = len(p)
return
}
There are some many advantages on using this syntax.
使用此语法有许多优点。
You don’t have to manually allocate the return variables, as having them named as result types, they are automatically initialized at their zero value for their type when the function begins.
您不必手动分配返回变量,因为将它们命名为结果类型,当函数开始时它们会自动以其类型的零值初始化。
Named return parameters do a very good job as implicit documentation: you know what the function is returning directly from its signature, as naming things help understand the code.
命名返回参数作为隐式文档非常出色:您知道函数直接从其签名返回什么,因为命名有助于理解代码。
If there are multiple exit points from a function, you don’t need to write all the parameters, just return
(called bare return). You still can list the returned values explicitly, and probably you should, to prevent having code hard to read. As suggested in The Go Programming Language:
如果一个函数有多个退出点,则无需编写所有参数,只需return
(称为裸返回 )。 您仍然可以显式列出返回的值,也许应该这样做,以防止难以阅读的代码。 如Go编程语言中所建议:
[…] with many return statements and several results, bare returns can reduce code duplication, but they rarely make code easier to understand. […] Bare returns are best used sparingly
[…]有很多return语句和几个结果,裸返回可以减少代码重复,但是很少使代码更易于理解。 […]最好谨慎使用裸露的退货
An example:
一个例子:
func something(n int) (ret int, m string, err error) {
if n == 0 {
err = errors.New("Houston, we have a problem!")
return 0, "", err
}
ret = n + 100
m = "Congratulations"
return ret, m, err
}
or with bare returns:
或没有回报:
func something(n int) (ret int, m string, err error) {
if n == 0 {
err = errors.New("Houston, we have a problem!")
return
}
ret = n + 100
m = "Congratulations"
return
}
In both cases the code is cleaner and more readable than
在这两种情况下,代码都比以下代码更整洁,更易读
func something(n int) (int, string, error) {
var ret int
var m string
if n == 0 {
err := errors.New("Houston, we have a problem!")
return ret, m, err
}
ret = n + 100
m = "Congratulations"
return ret, m, nil
}
Beware the risk of shadowing a parameter with a new declaration inside the function.
当心在函数内部使用新的声明对参数进行阴影处理的风险。
So, when should you use them? When it makes sense to you in the overall design of a program. I’ll let The Go Programming Language reply with a quote:
那么,什么时候应该使用它们? 在程序的总体设计中对您有意义。 我将用引号让Go编程语言回复:
[…] it’s not always necessary to name multiple results solely for documentation. For instance, convention dictates that a final
bool
result indicates success; anerror
often needs no explanation.[…]不一定总是只为文档命名多个结果。 例如,惯例规定最终的
bool
结果表示成功;error
通常不需要解释。
Additional resources:
其他资源:
https://stackoverflow.com/questions/45239409/empty-return-in-func-with-return-value-in-golang
https://stackoverflow.com/questions/45239409/empty-return-in-func-with-return-value-in-golang
api 返回参数 命名