Functions and Scopes
Understand the scope of variables and learn to create functions in Go.
Scopes
A scope is a program region where we can access a variable. We have local and global variables in Go. We can access local variables within the blocks we define them in. Global variables are accessible throughout the program.
Press + to interact
package mainimport "fmt"func main() {// local variablevar eggs,chickens integgs = 3chickens = 7fmt.Printf ("eggs = %d, chickens = %d\n", eggs,chickens)}
Let’s see an example of global variable declaration below:
Press + to interact
package mainimport "fmt"// global variablevar months int = 11func main() {fmt.Printf ("months = %d\n", months)}
It’s possible to have the same name for a local and a global variable, but the global variable becomes inaccessible in the scope of that local variable. The scope of the local variable starts from the line of declaration of that variable, and ends at the enclosing right brace, ...
Access this course and 1400+ top-rated courses and projects.