duanbi3385 2018-04-10 14:46 采纳率: 100%
浏览 78
已采纳

Go中的函数调用函数

package main

var a string

func main() {
   a = "G"
   print(a)
   f1()
}

func f1() {
   a := "O"
   print(a)
   f2()
}

func f2() {
   print(a)
}

I think f2 will be in f1's block when call f2 in f1, so the output will be GOO, but the output is GOG instead.

The scope of a type identifier declared inside a function begins at the identifier in the TypeSpec and ends at the end of the innermost containing block. -- From https://golang.org/ref/spec#Declarations_and_scope

What are containing blocks inside a function?

Why another function is not containing block?

  • 写回答

5条回答 默认 最新

  • dongqun9403 2018-04-10 14:55
    关注

    Your function f1 creates a new, local variable a which shadows the global variable a:

    func f1() {
       a := "O"
       print(a)
       f2()
    }
    

    That variable is scoped to f1. Any function it calls has its own scope, no scope change within f1 has any impact on any other function it calls (excepting closures). So, when f2 accesses a, it is accessing the global a. Otherwise, determining behavior would be nearly impossible because it would depend entirely on the calling context which can vary between different calls to the same function. If you want to pass some value to a function, pass it as a parameter.

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

报告相同问题?

悬赏问题

  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择
  • ¥15 这款软件是什么?需要能满足我的需求
  • ¥15 SpringSecurityOauth2登陆前后request不一致
  • ¥15 禅道二次开发编辑版本,上传不了发行包