Golang: Use one value in conditional from function returning multiple arguments

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

EDIT: See comment by Matt Mc


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.

Tags:

Go