Many Happy Returns

Coming from a Java background, it’s interesting to see multiple return types supported in Go functions.

Tour of Go

I figured the Tour of Go, would be an appropriate activity to get used to the language.

The example in chapter 6 demonstrates the function parameters piggybacking their type declaration (x, y, string) to be the last type listed.

Additionally, one gathers that the return type of (string, string) enclosed in parenthesis allows the langauge to support the multiple returns.

package main

import "fmt"

func swap(x, y string) (string, string) {
    return y, x
}

func main() {
    a, b := swap("hello", "world")
    fmt.Println(a, b)
}

Prints:

world hello

This is being run in the web console. After the tour is over, we’ll see where the files properly reside on the file system to be compiled with go build, etc.

These are illegal in Java

Fow now, it’s encouraging to imagine the ways multiple return types could be leveraged in future code, since (infrequently but recurringly) the urge occurs in Java to return two types.

The canonical way in Java is to declare a separate class for these cases, and have the function return that class, which will contain references to multiple objects.

Lately, I’ve been using a genericized (sp?) Tuple class in Java with a left and right type argument. While this saves the need to write a separate class in a separate file each time, it still feels clunky.

It’ll remain to be seen in practice how much the multiple return types are reached-for, but for now, it’s cool to have something new.

◀   Install Go Organizing Go Code   ▶