doutuo3899 2015-01-21 11:44
浏览 193
已采纳

Golang:函数的多个返回值的范围

When a function returns more than one variable in Golang, what's the scope of the variables? In the code attached, I can't figure out the scope of b.

package main

import (
    "fmt"
)

func addMulti(x, y int) (int, int) {
    return (x + y), (x * y)
}

func main() {
    //what is the scope of the b variable here?
    a, b := addMulti(1, 2)

    fmt.Printf("%d %d
", a, b)

    //what is the scope of the b variable here?
    c, b := addMulti(3, 4)

    fmt.Printf("%d %d
", c, b)

}   
  • 写回答

3条回答 默认 最新

  • douken0530 2015-01-21 11:51
    关注

    We're not talking about the scope of the return value of a function but rather the scope of the variable you assign the return value to.

    The scope of the variable b in your case is the function body, from the point at which you declare it.

    At first you do it at this line:

    a, b := addMulti(1, 2)
    

    But then you use another Short Variable declaration at this line:

    c, b := addMulti(3, 4)
    

    which - since b is already declared - just assigns a new value to it. b will be in scope until the end of your main() function. Quoting from the Go Language Specification:

    Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block with the same type, and at least one of the non-blank variables is new. As a consequence, redeclaration can only appear in a multi-variable short declaration. Redeclaration does not introduce a new variable; it just assigns a new value to the original.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于模型训练的一个问题
  • ¥15 装了几千台服务器从来没遇到这种问题,哎看下哪位帮我解决吧
  • ¥15 单片机程序上的困难问题
  • ¥15 请教某软件缓存Ts文件破解合并mp4的方法
  • ¥15 求小游戏炸弹人中关于敌人的C++代码
  • ¥15 拿到这个服务器最高权限有偿
  • ¥50 来个抓app跳转支付宝转链接的
  • ¥15 remotes安装提示没有description文件
  • ¥15 AttributeError: 'NoneType' object has no attribute 'drop_duplicates'报错
  • ¥15 以下代码,运行结果报错