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

报告相同问题?

悬赏问题

  • ¥18 模拟电路问题解答有偿
  • ¥15 Matlab在app上输入带有矩阵形式的初始条件发生错误
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题