When we talk about scope in any programming language, we are referring to how the code can access variables. Scope defines where a variable can be accessed based on how it is declared. Scope in Go is fairly simplistic. In this post, we will be talking about scope in Go.

Go has three specific types of variables: local variables, global variables and formal parameters. First of all, local variables are found inside of a block or function. Also, global variables are found outside of all functions. Finally, formal parameters are the variables in function definitions.

scope

Local Variables

Local variables are the most common type in Go. They can only be used by the statements that are in the block of code in which they were made. This is to say that local variables are not accessible by functions outside of their own. Look at the example below.

These variables are bound to the main function. They can’t be accessed by a function or block of code outside of the main function.

Global Variables

Global variables are typically defined outside of all functions and at the top of the program. This style of defining a variable at the top is idiomatic in Go. Global variables have a lifetime that last as long as the program runs. They also can be accessed by any function in the program that follows their declaration.

In this program, both of the functions have access to our global variable. This has its advantages and disadvantages. Consequently, any function has access to this variable which means any function can change this variable.

scopeFormal Function Parameters

Finally, we have formal parameters. These variables are treated like local variables and they gain preference over global variables. Therefore, if the global variable shares the name of a formal function parameter the formal parameter will be used. So, Let us look at an example of this.

In this somewhat nonsensical program, we have three variables that share the name, g. One is a global variable, one is a local variable and the other is a formal parameter. We are also calling the references for these variables to show that they are different. This reference notation is something we will look at closer in our next post. For now, all you need to know is that the three values are different from one another. Furthermore, each time we print the reference to g out, we are calling a different block of memory. 

Conclusion

In this post, we looked at scope in Go. We looked at local variables, global variables and formal functional parameters in Go. We touched briefly on pointers and references in this post as well. In our next posts, we will be going over Pointers and References in Go.