Pair/tuple data type in Go


I need a queue of (string, int) pairs. That’s easy enough:

type job struct {
    url string
    depth int

queue := make(chan job)
queue <- job{url, depth}

are there built-in pair/tuple data types in Go? There is support for returning multiple values from a function, but AFAICT, the multiple value tuples produced are not first-class citizens in Go’s type system. Is that the case?

As for the "what have you tried" part, the obvious syntax (from a Python programmer’s POV)

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

didn’t work.


There is no tuple type in Go, and you are correct, the multiple values returned by functions do not represent a first-class object.

Nick’s answer shows how you can do something similar that handles arbitrary types using interface{}. (I might have used an array rather than a struct to make it indexable like a tuple, but the key idea is the interface{} type)

My other answer shows how you can do something similar that avoids creating a type using anonymous structs.

These techniques have some properties of tuples, but no, they are not tuples.

Answered By – Sonia

Answer Checked By – Pedro (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.