go - 为什么要命名返回参数?

标签 go return return-value

命名函数的返回参数有什么好处?

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/

相关文章:

javascript - 返回 Node.js 函数的值

mysql - 使用node.js执行查询后返回MySQL结果

Python 返回值?

go - 如何使用 Golang 获取 UTC 时间的时间戳?

go - 如何在不使用 time.Sleep 的情况下等待所有 goroutines 完成?

pointers - 通过将指针传递给 Go 中的函数来获取不同的值

java - 为返回的字符串值设置参数

接收字符串的 Python 函数,返回字符串 + "!"

c# - 如何在 C# 中设置值 float?

go - 是否有必要明确提及变量的类型?