将函数的值作为输入参数返回给另一个 [英] Return values of function as input arguments to another
问题描述
如果我有
func returnIntAndString() (i int, s string) {...}
我有:
func doSomething(i int, s string) {...}
然后我可以成功完成以下操作:
Then I can do the following successfully:
doSomething(returnIntAndString())
但是,假设我要向doSomething添加另一个参数,例如:
However, let's say I want to add another argument to doSomething like:
func doSomething(msg string, i int, s string) {...}
如果我这样称呼,Go在编译时会抱怨:
Go complains when compiling if I call it like:
doSomething("message", returnIntAndString())
使用:
main.go:45: multiple-value returnIntAndString() in single-value context
main.go:45: not enough arguments in call to doSomething()
有没有办法做到这一点,还是我应该放弃并将returnIntAndString
的返回值分配给某些引用,并传递msg和这些值,例如doSomething(msg, code, str)
?
Is there a way to do this or should I just give up and assign the return values from returnIntAndString
to some references and pass msg and these values like doSomething(msg, code, str)
?
推荐答案
在规范中中进行了描述一个>.它要求内部函数返回所有参数的正确类型.没有多余的参数以及返回多个值的函数.
It's described here in the spec. It requires the inner function to return the correct types for all arguments. There is no allowance for extra parameters along with a function that returns multiple values.
在特殊情况下,如果函数或方法g的返回值为 数量相等,可分别分配给以下参数 另一个函数或方法f,则调用f(g(parameters_of_g))将 将g的返回值绑定到f的参数后调用f 为了. f的调用除调用外不得包含任何参数 g的值,并且g必须至少具有一个返回值.如果f具有最终值... 参数,分配给g的返回值保留在 常规参数的分配.
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")
}
如果不满足这些特定条件,则需要分配返回值并分别调用该函数.
If those specific conditions are not met, then you need to assign the return values and call the function separately.
这篇关于将函数的值作为输入参数返回给另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!