Go / Tuple Data Type in Go

Performing the final Tour of Go exercise , I decided that I needed a queue ( string , int ). This is easy enough:

 type job struct { url string depth int } queue := make(chan job) queue <- job{url, depth} 

But it made me wonder: are there any built-in pair / tuple data types in Go? There is support for returning multiple values from a function, but AFAICT received multiple tuples are not first-class citizens in a system like Go. Is this the case?

As for the โ€œwhat have you triedโ€ part, the obvious syntax is (from the POV programmer POV)

 queue := make(chan (string, int)) 

does not work.

+46
go tuples pair
Dec 02
source share
3 answers

There is no tuple type in Go, and you're right, the multiple values โ€‹โ€‹returned by functions do not represent an object of the first class.

Nick's answer shows how you can do something like this that handles arbitrary types using the {} interface. (I could use an array rather than a structure to make it indexable like a tuple, but the interface type {} is a key idea.)

My other answer shows how you can do something like this, which avoids creating a type using anonymous structures.

These methods have some tuple properties, but no, they are not tuples.

+21
Dec 03
source share

Can you do it. It looks more verbose than a tuple, but it's a big improvement because you get type checking.

Edit: Replaced a fragment with a full working example, following Nick's suggestion. Link to the playing field: http://play.golang.org/p/RNx_otTFpk

 package main import "fmt" func main() { queue := make(chan struct {string; int}) go sendPair(queue) pair := <-queue fmt.Println(pair.string, pair.int) } func sendPair(queue chan struct {string; int}) { queue <- struct {string; int}{"http:...", 3} } 

Anonymous structures and fields are great for quick and dirty decisions. However, for all but the simplest cases, you better define a named structure, just like you.

+51
Dec 02
source share

You can do something like this if you want

 package main import "fmt" type Pair struct { a, b interface{} } func main() { p1 := Pair{"finished", 42} p2 := Pair{6.1, "hello"} fmt.Println("p1=", p1, "p2=", p2) fmt.Println("p1.b", p1.b) // But to use the values you'll need a type assertion s := p1.a.(string) + " now" fmt.Println("p1.a", s) } 

However, I think that you are already completely idiomatic, and the structure perfectly describes your data, which is a big advantage compared to using simple tuples.

+14
Dec 02 '12 at 16:15
source share



All Articles