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()
returnIntAndStringdoSomething(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.

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屋!