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

时间:2019-02-12 17:34:25

标签: go

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

package main

import (

    "fmt"
)

func Smile(){
  A := 5
}

func main() {

   fmt.Println(A)

}

这给我未定的A。

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

2 个答案:

答案 0 :(得分:3)

无法从A打印在Smile()函数中声明的main()变量的值。

其主要原因是变量A仅在代码执行进入Smile()函数,更确切地说到达A变量声明时才存在。在您的示例中,这永远不会发生。

即使在其他示例中发生这种情况(例如,调用Smile()),应用程序也可能具有多个goroutine,而其中的多个goroutine可能同时在执行Smile(),从而导致具有多个彼此独立的A变量的应用程序。在这种情况下,A中的main()将引用哪个

Go is lexically scoped using blocks.这意味着在A中声明的变量Smile()仅可从Smile()访问,main()函数无法引用它。如果需要这种“共享”,则必须在A之外定义Smile()。如果Smile()main()都需要访问它,则必须将其设置为全局变量,或者将其传递给需要它的函数。

将其设置为全局变量,如下所示:

var a int

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

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

这将输出(在Go Playground上尝试):

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

main()中将其声明为本地并将其传递给smile(),这就是它的样子:

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

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

输出(在Go Playground上尝试):

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

答案 1 :(得分:1)

最好的方法是https://godoc.org/golang.org/x/tools/go/pointer

  

指针

例如:

    /* Hi, Welcome to stack overflow.
     * The reason why you only see the button 2 is because it is overlapping one another.
     * I would suggest you to look through the layoutManager https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html and really get your hands dirty
     * There are many ways of getting your desired result, you can do it with GridBagLayout but i would suggest you create JPanel and make it as a container
     * The reason why you only see the button 2 is because it is overlapping one another 
     */

public static void main(String[] args){

    //Variable 
    JTextField field = new JTextField(10);
    JButton btn = new JButton("Enter");
    JTextArea area = new JTextArea(50,50);

    //-- Main frame
    JFrame frame = new JFrame("Testing");
    //IF you need a specific size , you can set your preferred size to your jframe
    //otherwise , you can just use frame.pack() at the end of the code 
    //frame.setSize(300,300);
    frame.setLayout(new BorderLayout());

    //-- Top Container
    JPanel topContainer = new JPanel();
    topContainer.setLayout(new FlowLayout());
    topContainer.add(field);
    topContainer.add(btn);

    // Now add your container to your main frame 
    frame.add(topContainer,BorderLayout.PAGE_START);
    frame.add(area,BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
}