Golang将函数的值作为输入参数返回给另一个 [英] Golang return values of function as input arguments to another

查看:1165
本文介绍了Golang将函数的值作为输入参数返回给另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有

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

我有:

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

然后我可以做以下是成功的:

  doSomething(returnIntAndString())


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

如果我这样称呼它:

  doSomething(message,returnIntAndString())
  main.go:



45:单值上下文中的多值returnIntAndString()
main.go:45:调用doSomething()时没有足够的参数()

有没有办法做到这一点,或者我应该放弃并分配返回值 returnIntAndString 给一些引用并传递msg,并且这些值像 doSomething(msg,code,str)

解决方案

这里描述了规格。它需要内部函数为所有参数返回正确的类型。没有额外参数的允许以及返回多个值的函数。
$ b


作为一种特殊情况,如果函数或方法g的返回值是
的数目相等并可单独分配给参数
的另一个函数或方法f,那么调用f(g(parameters_of_g))将
调用f,将g的返回值按顺序绑定到f
的参数。 f的调用除g的调用
之外,不能包含其他参数,并且g必须至少有一个返回值。如果f有一个最终的...
参数,它将被分配到常量参数
分配后剩下的g的返回值。

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

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

如果加入(Split(value,len(value)/ 2))! = value {
log.Panic(test failed)
}


如果不满足这些特定条件,则需要分配返回值并分别调用该函数。

If I have

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

And I have:

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

Then I can do the following successfully:

doSomething(returnIntAndString())

However, let's say I want to add another argument to doSomething like:

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

Go complains when compiling if I call it like:

doSomething("message", returnIntAndString())

With:

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

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.

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.

这篇关于Golang将函数的值作为输入参数返回给另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆