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

在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?

图片转代码服务由CSDN问答提供 功能建议

我知道变量在go中通过值传递。 但是,我想在该函数之外的func内部调用一个变量。 让我举个例子:

 包main 
 
import(
 
“ fmt” 
)
 
func Smile(){
 A:  = 5 
} 
 
func main(){
 
 fmt.Println(A)
 
} 
   
 
 

这给了我未定义的A

通过A的最佳方法是什么? 我应该使用指针吗? 我该怎么办?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题