Golang – using function with multiple return values in a return statement

huangapple go评论67阅读模式
英文:

Golang - using function with multiple return values in a return statement

问题

如果我在Go语言中有一个嵌套函数:

findDups := func(groups []string) (int, string) {
    dupCnt := 0
    dups := ""
    prevGroup := ""
    for _, group := range groups {
        if group == prevGroup {
            dupCnt++
            dups += group + ", "
        }
        prevGroup = group
    }
    return dupCnt, dups
}

在语言中是否有一种方式可以从"外部"/父函数的返回语句中调用这个函数,例如:

return findDups(sourceGroups), findDups(targetGroups)

父函数的返回签名是(int, string, int, string)。编译器报错并显示以下消息:

2-valued findDups(sourceGroups) (value of type (int, string)) where single value is expected

我可以通过创建四个变量来处理这个问题,将内部函数的返回值赋给这些变量,并在返回语句中使用它们,但我想知道是否有更直接的方法。我尝试过在Google上搜索,但似乎无法形成正确的问题。

英文:

If I have an "inner"/nested function in Go:

	findDups := func(groups []string) (int, string) {
		dupCnt := 0
		dups := ""
		prevGroup := ""
		for _, group := range groups {
			if group == prevGroup {
				dupCnt++
				dups += group + ", "
			}
			prevGroup = group
		}
		return dupCnt, dups
	}

Is there a way in the language where I can call this function from the "outer"/parent function's return statement, e.g.:

return findDups(sourceGroups), findDups(targetGroups)

The parent function's return signature is (int, string, int, string). The compiler is complaining with the message:

> 2-valued findDups(sourceGroups) (value of type (int, string)) where single value is expected

I can deal with this by just creating four variables with the return values from the two calls to the inner function and using them in the return statement, but wondered if there's a more direct way of doing this. I've tried Googling it but can't seem to form the right question.

答案1

得分: 2

规范对你的选项非常清楚(我强调):

  1. 返回值可以在 "return" 语句中明确列出。
  2. "return" 语句中的表达式列表可以是对多值函数的单个调用
  3. 如果函数的结果类型为其结果参数指定了名称,则表达式列表可以为空。
英文:

The spec is pretty clear on what your options are (emphasis mine):

> 1. The return value or values may be explicitly listed in the "return" statement.
> 2. The expression list in the "return" statement may be a single call to a multi-valued function.
> 3. The expression list may be empty if the function's result type specifies names for its result parameters.

huangapple
  • 本文由 发表于 2022年2月11日 04:07:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/71071626.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定