douluxia0606 2016-02-08 16:31
浏览 282
已采纳

Golang返回函数的值作为另一个的输入参数

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) ?

  • 写回答

1条回答 默认 最新

  • dtu72460 2016-02-08 16:36
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看