将函数的返回值作为输入参数传递给另一个函数

17

如果我有

func returnIntAndString() (i int, s string) {...}

而我有:

func doSomething(i int, s string) {...}

然后我可以顺利地执行以下操作:

doSomething(returnIntAndString())

然而,假设我想像这样为doSomething添加另一个参数:

func doSomething(msg string, i int, s string) {...}

如果我像这样调用Go,编译时会抱怨:

doSomething("message", returnIntAndString())

使用:

main.go:45: multiple-value returnIntAndString() in single-value context
main.go:45: not enough arguments in call to doSomething()

有没有办法这样做,还是我应该放弃,并将returnIntAndString的返回值分配给一些引用并像doSomething(msg,code,str)这样传递msg和这些值?


如果您能发布剩余的代码,那将非常有帮助。 - thewhitetulip
2个回答

18

这在规范中有所描述。它要求内部函数对所有参数返回正确的类型。如果一个函数返回多个值,则不允许额外的参数。

As a special case, if the return values of a function or method g are equal in number and individually assignable to the parameters of another function or method f, then the call f(g(parameters_of_g)) will invoke f after binding the return values of g to the parameters of f in order. The call of f must contain no parameters other than the call of g, and g must have at least one return value. If f has a final ... parameter, it is assigned the return values of g that remain after assignment of regular parameters.

func Split(s string, pos int) (string, string) {
  return s[0:pos], s[pos:]
}

func Join(s, t string) string {
  return s + t
}

if Join(Split(value, len(value)/2)) != value {
  log.Panic("test fails")
}
如果不满足这些特定条件,那么您需要分别指定返回值并调用该函数。

1

我有同样的问题。我能想到的最好的解决方案是创建类型或结构体来存储我需要的额外参数,并编写类似于以下方法:

package main

import (
    "fmt"
)

type Message string

type MessageNumber struct {
    Message string
    Number int
}

func testfunc() (foo int, bar int) {
    foo = 4
    bar = 2
    return
}

func (baz Message) testfunc2(foo int, bar int) {
    fmt.Println(foo, bar, baz)
}

func (baz MessageNumber) testfunc3(foo int, bar int) {
    fmt.Println(foo, bar, baz.Number, baz.Message)
}

func main() {
    Message("the answer").testfunc2(testfunc())
    MessageNumber{"what were we talking about again?", 0}.testfunc3(testfunc())
    fmt.Println("Done.  Have a day.")
}

输出结果如下:

user@Frodos-Atari-MEGA-STE:~/go/test$ go run main.go
4 2 the answer
4 2 0 what were we talking about again?
Done.  Have a day.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接