dousui6488 2016-12-10 13:45 采纳率: 100%
浏览 175
已采纳

如何在Go lang函数中使用可变参数将返回多个值的参数传递给其他函数[重复]

This question already has an answer here:

I am new to go programming,

Assume this code, where in function fmt.Printf() passing two different values

package main

import "fmt"

func main() {
   var a int = 150
   var b int = 130
   var ret1, ret2 int
   ret1, ret2 = max(a, b)
   fmt.Printf( "Max val: %d Min val: %d
", ret1, ret2 )
}

func max(num1, num2 int) (int,int) {
   if (num1 > num2) {
      return num1, num2
   } else {
      return num2, num1
   }
}

Instead of passing ret1, ret2 in fmt.Printf( "Max val: %d Min val: %d ", ret1, ret2 ) is there any way, I can directly pass max(a, b) in fmt.Printf() like

fmt.Printf( "Max val: %d Min val: %d
", max(a, b))

I had tried it, it is giving error

multiple-value max() in single-value context

As it seems, returning two different values not a tuple, is my concept for this returning is wrong or I am doing it wrong.

Is there any method to pass function with multiple return directly to function require variable number of values

TIA

</div>
  • 写回答

2条回答 默认 最新

  • doupu9251 2016-12-10 13:50
    关注

    From the specification:

    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.

    The problem with the call that you want to make is that one of the arguments to Printf is not a return value of max. This call does work work:

    fmt.Println(max(a, b))
    

    https://play.golang.org/p/ZZayVkwZJi

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么