A scope in Golang is the region of a program where a defined variable can exist, and beyond that, a variable cannot be accessed. The Scope of the variable can be defined as a part of the program where the specific variable is accessible. A variable can be defined in the class, method, loop, etc. Just Like C/C++, in Go, all identifiers are lexically (or statically) scoped, for example, the scope of the variable can be determined at compile time.

Scope of Variables In Golang
There are three places where the variables can be declared in Golang.

  • Local variables
  • Global variables
  • Formal parameters

Let us deep dive what are local and global variables and what are formal parameters.

Local variables in Golang

Local variables are those that declared inside a function or a block. Local variables can be used only by statements that are inside that function or block of code.

However, these variables can be accessed by a nested code block inside the function.

These variables are also called as the block variables.

There will be the compile-time error if these variables are declared twice with a same name in the same scope.

#go #golang

Scope of Variables In Golang | Go Variables Scope
2.10 GEEK