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 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了