What is the three scopes in Go programming language

In Go programming language, there are three scopes for the variables which are:

1. code-block scope (local scope)
2. package scope (package-level scope)
3. outside-package scope (global scope)

The first scope is the local variable which initialized and used inside a function only. It can't be accessed outside this function block of code. For example:

package main
import "fmt"
func main() {
   a := 10
   fmt.Printf(a)
}
The variable a inside the function can't be accessed outside the function because it is a code-block scoped variable or local variable.

The second scope is the package scope. The variable is declared at the package level; above all the functions at the top of the code blocks. This variable name must start with a small case letter because if its first letter is a capital one, it will be a global scoped variable which can be accessed outside the package. For example:

package main
import "fmt"
var b int
func main() {
   b = 20
   fmt.Printf(b)
}

The variable b in the above example is a package scope variable as it can be used inside the package main only. No other packages can access or use this variable.

But the third scope is the global scope (a.k.a outside package scope). The name of the variable must start with a capital letter. For example:

package main
import "fmt"
var Num int
func main() {
   Num = 20
   fmt.Printf(Num)
}

The variable Num is a global variable which we can access from another package and use it normally. That's why we use a pascal case when calling a variable from a dependency package inside our Go program code.

I hope you learn something. If you want to get new posts, make sure to subscribe to Value In Brief by Email.
Comment via Facebook
0 Comment via Google

0 تعليقات:

Post a Comment