Go返回多个值时究竟发生了什么 [英] What exactly is happening when Go returns multiple values

查看:83
本文介绍了Go返回多个值时究竟发生了什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  func learnMultiple(x,y int)(sum,prod int)函数和方法可以返回多个值。 {
return x + y,x * y //返回两个值
}

sum,prod:= learnMultiple(10,50)

它与返回一个元组相似吗?

我来自红宝石土地,我可以返回一个数组和

  sum,prod = [60,500 ] 


解决方案

我们可以轻松地查看一些编译的代码来确认

请考虑以下代码片段:

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

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

如果我们反汇编创建ELF二进制文件,你会看到类似的内容(内联被禁用,所以我们可以看到调用发生):

  000 0000000400c00< 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
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
(...)

所以 f 只是将结果字节放入堆栈中, main 将它们选中并放入工作寄存器中。一个不同的编译器也可能选择将这些值在两个范围之间直接传递到寄存器中。



这与C语言的编译器所做的相似,除了它的规范只定义了一个返回值。


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"]

解决方案

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.

这篇关于Go返回多个值时究竟发生了什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆