Search⌘ K
AI Features

Scope of Variables

Explore the scope of variables in Go programming by understanding global and local scopes, how variable shadowing works, and the difference between value and reference types. This lesson explains memory allocation in stack and heap, helping you grasp how variable scope impacts Go programs.

Scope of a variable

A variable of any type is only known in a certain range of a program, called its scope. In a programming language, there are two main types of scopes:

  • Global scope
  • Local scope

Global scope

The scope of the variables declared outside of any function (in other words at the top level) is called global scope. Global scope is also known as package scope because the variables with such scope are visible and available in all source files of a package.

Local scope

The scope of the variables declared inside a function is called local scope. They are only known in that function; the same goes for parameters and return variables of a function.

In simple words, mostly, you can think of a scope ...