What is Package level Variable in Golang

In programming, there are two types of variable scopes.

  1. Local scope
  2. Global scope

The local scope of a variable’s access is limited, and it is bound to just functions or methods it is defined into.

The scope of a global variable is package level, which you cannot declare inside any function or method. Instead, you need to define it outside any function and have access to that variable anywhere within the package.

How to create a variable in Go

To create a variable in Golang, use the var name [type] = expression syntax. The type or the expression may be skipped, but not both at the same time; otherwise, it will throw an error.

package main

import (
  "fmt"
)

func main() {
  var barry int = 21
  var mindy bool = true
  fmt.Println(data)
  fmt.Println(mindi)
}

Output

21
true

You can see that we created two variables inside the main() functions. One is an integer type, and another is a boolean type.

Using the fmt.Println() function, we printed both variables’ values to the console.

Golang package level variable

Go package-level variable is a variable that is defined outside of any function or method. 

A package-level variable is visible to all functions and methods within the package and can be accessed using the variable’s name.

package main

import (
  "fmt"
)

var data int = 21

func main() {
  fmt.Println(data)
}

Output

21

We defined an integer variable “data” at the package level and not inside a function, but we are accessing the “data” variable inside the main() function.

We can access a variable inside the main() function because the variable is package-level and not at any function level. That’s why it is a global variable that can be accessed anywhere in the script.

Advantages of package-level variables

Package-level variables are valuable for storing values that need to be shared across multiple functions or methods within a package.

Package-level variables can be accessed and modified from any function or method within the package but are not accessible outside the package.

Conclusion

To create a packagelevel variable in Golang, declare a variable outside any function or method. Then it will become a package-level variable; you can access it anywhere in your package because the scope is bigger and wider now.

That’s pretty much it for this article.

Leave a Comment