Golang 101: Scopes

The Gopher
2 min readJul 20, 2023

--

The variables in go have two scopes: global and local.

Global scope: Variables declared outside of the functions can be accessed in multiple functions

Local scope: Variables declared within the function are only limited to only that function block.

Global variables in Go:

package main

import "fmt"

var num int // num is a global variable here

func main() {
num = 10
fmt.Println(num)

addTen()
fmt.Println(num)
}

func addTen() {
num += 10
}

Notice how we modified num in the addTen function. We should see 10 and 20 are printed as output.

Local Variables in Go:

package main

import "fmt"

var num int // num is a global variable here

func main() {
num = 10
fmt.Println(num)
local()
}

func local() {
num := 100 // here num is a local variable which is created in the function
fmt.Println(num)
}

We created a new local variable num with shorthand syntax (:=) in the local function. This does not collide with the global num variable. If we run the program we should see 10 followed by 100 printing as output.

Quick Puzzle to test your knowledge

What is the output of the following program? Let me know in the comments section

package main

import "fmt"

var num int

func main() {
num = 10
fmt.Println(num)
local()
fmt.Println(num)
}

func local() {
num := 100
fmt.Println(num)
num = 200
fmt.Println(num)
}

--

--

The Gopher
The Gopher

Written by The Gopher

A go language enthusiast. Contact coderethinked509@gmail.com for anything or to just say fmt.Println('Hi')

No responses yet