Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly is happening when Go returns multiple values

Tags:

go

Go functions and methods can return multiple values.

func learnMultiple(x, y int) (sum, prod int) {
    return x + y, x * y // return two values
}

sum, prod := learnMultiple(10, 50)

Is it similar to returning a tuple?

I come from ruby land where I can return an array and a

sum, prod = ["60","500"]
like image 487
Stephen Nguyen Avatar asked Sep 04 '13 19:09

Stephen Nguyen


2 Answers

We can easily look at some compiled code to confirm what's going on behind the scenes.

Consider this snippet:

func f() (a, b byte) {
    return 'x', 'y'
}

func main() {
    a, b := f()
    println(a, b)
}

If we disassemble the created ELF binary, you'll see something like this (inlining was disabled so we could see the call happening):

0000000000400c00 <main.f>:
400c00:       c6 44 24 08 78          movb   $0x78,0x8(%rsp)
400c05:       c6 44 24 09 79          movb   $0x79,0x9(%rsp)
400c0a:       c3                      retq

0000000000400c10 <main.main>:
(...)
400c25:       48 83 ec 10             sub    $0x10,%rsp
400c29:       e8 d2 ff ff ff          callq  400c00 <main.f>
400c2e:       48 0f b6 1c 24          movzbq (%rsp),%rbx
400c33:       48 89 d8                mov    %rbx,%rax
400c36:       48 0f b6 5c 24 01       movzbq 0x1(%rsp),%rbx
(...)

So f just puts the result bytes in the stack, and main picks them back and puts them in working registers. A different compiler might also choose to pass these values around between the two scopes straight into registers.

This is all similar to what a compiler for the C language would do, except its specification defines a single return value only.

like image 114
Gustavo Niemeyer Avatar answered Nov 02 '22 23:11

Gustavo Niemeyer


It is similar to returning a tuple, in the sense that some languages (like python) use tuples to implement multiple return values.

But in Go there is no such thing as a tuple. A function that returns one value allocates one slot on the stack to hold it. A function that returns two values allocates two slots on the stack to hold them. And so on…

like image 26
andybalholm Avatar answered Nov 03 '22 01:11

andybalholm