如何在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>

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

You can do something similar with an inline helper function with a variadic parameter.

package main

import "fmt"

func main() {
   var a int = 150
   var b int = 130
   func(i ...int){fmt.Printf( "Max val: %d Min val: %d
", i[0], i[1] )}(max(a,b))
}

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

I hope it helps.

Look at https://play.golang.org/p/tB-q8hjNdu to see it in action.