Friday, November 13, 2009

One Feature of Go that Every Programming Language Needs to Have

Named return values. They rock.

func doit(x int) (a int, b int) {
// do stuff
a = 1;
b = 2;

// call it like this:
a, b = doit(x);

In the languages I use, there are two ways to return multiple values from a function:
  1. Build an array, tuple, or dictionary with the return values. That's wasteful and the compiler won't catch your errors.

  2. Pass in reference or pointers. But that's not as elegant as Go's solution: You have to look twice to realize the function call will change the value of your variables.

I'd love to see this in other languages as well.

Thanks to Mark Chu-Carroll for his excellent intro article. More about multiple return values in Go in the language reference.


Galtenbergs said...

Why would you want a function to determine the var names used in the consuming method? Maybe 'count' to you means 'numFriends' to me.

Ruby allows multiple ordered return values. So you can do the exact same thing without having to write anything extra in the interface -- just say 'return a, b'

Gabor said...

The (a int, b int) in the function interface just defines the local name. When you call the function, you can name the variables that are assigned to anything you want.

Daniel said...

LUA has something similar with multiple return values.

The most interesting are usually returned first and if you want to ignore some you can use the all powerful _ variable name from many functional programming languages.