Golang:在函数中使用一个值返回多个参数

Suppose in Go we have a function returning two arguments

func squareAndCube(int side) (square int, cube int) {
    square = side * side
    cube = square * side
    return
}

Then you would like to use the first (second) value of this function in the conditional:

square, _ := squareAndCube(n)
if square > m {
    ...
}

However, can we do first two lines in one line if we do not need the value square to use anywhere else? E.g.

 if squareAndCube(n).First() > m {
     ...
 }

You cannot pick one of the multiple returned values but you can write something like

if square, _ := squareAndCube(n); square > m {
    // ...
}

The square variable will only be valid in the if scope. These "simple statements" can be used in if statements, switch statements and other constructs such as for loops.

See also the effective go article on if statements.

Found this blog post by Vladimir Vivien that has a nice workaround for the problem. The solution is to create a function that "...exploits the automatic conversion from the compiler to convert a vararg parameters in the form of "x...interface{}" to a standard []interface{}."

func mu(a ...interface{}) []interface{} {
    return a
}

Now you can wrap any function with multiple returned values in mu and index the returned slice followed by a type assertion

package main

import(
    "fmt"
)

func mu(a ...interface{}) []interface{} {
    return a
}

func myFunc(a,b string) (string, string){
    return b, a
}

func main(){
    fmt.Println(mu(myFunc("Hello", "World"))[1].(string))
}

// output: Hello