Variable declaration — GoLanguage

Always learning
3 min readJun 5, 2024

Variable declaration which allocates storage for that variable.

use the var keyword followed by a name and its data type. This variable can be assigned later in the program.

  • var varName type = value
  • varName := value

buymeacoffee ☕ 👈 Click the link

Variables can be defined in various scopes:

  • Local: Inside a function or block, only accessible within that function.
  • Package: Outside a function but inside a package, accessible throughout the package.
  • Global: Declared outside a function, accessible throughout the program.
  • Exported/Unexported: Variables starting with an uppercase letter are exported and can be accessed from other packages. Those with lowercase are unexported and are private to their package.

Example 1

package main

import "fmt"

func main() {
var a int
a = 10
fmt.Printf("%d", a)
}

fmt stands for the Format package. This package allows to format basic strings, values, or anything and print them or collect user input from the console.

Example 2

package main

import "fmt"

func main() {
var a int = 20
fmt.Printf("%d", a)
}

This declares a variable named a of type int. You can also assign a value during declaration.

Example 3

Short declaration operator

Short variable declarations. Inside a function, the := short assignment statement can be used in place of a var declaration with implicit type.

package main

import "fmt"

func main() {
a := 30
fmt.Printf("%d", a)
}

Basic assignment operator is = . However, there are shorthand operators that combine arithmetic and assignment, which not only make the code more concise but also improve its readability. These include: += : Adds and assigns.

Example 4

package main

import "fmt"

func main() {
a, b := 30, 40
fmt.Printf("%d %d", a, b)
}

If a variable is not assigned any value, Go automatically initializes it with the zero value of the variable’s type. In this case, age is assigned the value 0 , which is the zero value of int.

You have declared a variable in the code but did not used it anywhere. This makes the code crash because go wants you to write clean code which is easy to understand and use every variable you declare.

Thank you 🙏 for taking the time to read our blog.

--

--

Always learning

கற்றுக் கொள்ளும் மாணவன்...