From multiple to single-value context in Go

These are the results of exploring one aspect of the Go language; functions can return multiple values. Consider the following simple function:

func ab() (a,b int) {
    a,b = 1,2
    return
}

Clearly, this function cannot be used in other function calls that expect a single value.

fmt.Printf("%v\n",ab())

The compiler will help you: “multiple-value ab() in single-value context”.

Now suppose you want to take only the first value without introducing an intermediate variable. One possible solution might be to create this helper function:

func first(args …interface{})interface{} {
    return args[0]
}

Such that you can write:

fmt.Printf("%v\n",first(ab()))

But what if you want to generalize this such that you won’t end up with functions like second(),third(),… To achieve this, I tried the following:

func pick(index int, args …interface{})interface{} {
    return args[index]
}
fmt.Printf("%v\n",pick(1,ab()))

However, again the compiler prompts with the same error message: “multiple-value ab() in single-value context”. It is my interpretation that the compiler (in this case) cannot implicitly convert the multiple returns into a slice because of the extra function parameter.

So instead I created this slice converter function:

func slice(args …interface{}) []interface{} {
    return args
}

And with that, you can write:

fmt.Printf("%v\n",slice(ab())[1])

comments powered by Disqus