dqydp44800 2019-02-12 17:34
浏览 604
已采纳

在go中从另一个函数调用变量

I know that variables are pass by value in go. However, I want to call a variable that in inside a func outside this function. Let me give you an example:

package main

import (

    "fmt"
)

func Smile(){
  A := 5
}

func main() {

   fmt.Println(A)

}

This gives me undefine A.

what is the best way to pass A ? Should I use a pointer? How do I do that?

  • 写回答

1条回答 默认 最新

  • dpntq48842 2019-02-12 17:41
    关注

    It's not possible to print the value of the A variable declared in the Smile() function from main().

    And the main reason for that is that the variable A only exists if code execution enters the Smile() function, more precisely reaches the A variable declaration. In your example this never happens.

    And even if in some other example this happens (e.g. Smile() is called), an application may have multiple goroutines, and multiple of them may be executing Smile() at the same time, resulting in the app having multiple A variables, independent from each other. In this situation, which would A in main() refer to?

    Go is lexically scoped using blocks. This means the variable A declared inside Smile() is only accessible from Smile(), the main() function cannot refer to it. If you need such "sharing", you must define A outside of Smile(). If both Smile() and main() needs to access it, you have to make it either a global variable, or you have to pass it to the functions that need it.

    Making it a global variable, this is how it could look like:

    var a int
    
    func smile() {
        a = 5
        fmt.Println("a in smile():", a)
    }
    
    func main() {
        smile()
        fmt.Println("a in main():", a)
    }
    

    This outputs (try it on the Go Playground):

    a in smile(): 5
    a in main(): 5
    

    Declaring it local in main() and passing it to smile(), this is how it could look like:

    func smile(a int) {
        fmt.Println("a in smile():", a)
    }
    
    func main() {
        a := 5
        fmt.Println("a in main():", a)
        smile(a)
    }
    

    Output (try it on the Go Playground):

    a in main(): 5
    a in smile(): 5
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)