Declaring Variables in Go Programming Language

In Go, variables hold data of specific types such as integers, floating-point numbers, or booleans. Every variable must be declared before use and carries an explicit type.

Go supports several forms of variable declaration:

Explicit Type Declaration

Variables are introduced with the var keyword followed by name and type. No semicolon is required at line end.

var userName string
var itemCount int
var isValid bool

Grouped Declaration

Multiple variables can be declared together with in parentheses to reduce repetition.

var (
    userName string
    itemCount int
    isValid   bool
)

Type Inference

When initial value is provided, the compiler infers the type, allowing omission of the explicit type specifier.

var userName, isValid = "BubbleDrink", true

Declaration with Initialization

A variable can be declared and assigned a starting value in one step. If no value is given, it receives the zero value for its type: numeric types default to 0, strings to "", booleans to false, and composite types likee slices, functions, or pointers default to nil.

var userName string = "BubbleDrink"
var userAge int    = 25
var userName, isValid = "BubbleDrink", true

Short Declaration Inside Functions

Within function bodies, the := operator declares and initializes a variable without using var. This form is limited to local scope.

package main

import "fmt"

var globalCounter = 20

func main() {
    localCounter := 5
    globalCounter := 200 // shadows the outer variable
    fmt.Println(localCounter, globalCounter)
}

Ignoring Return Values Using Blank Identifier

To discard unwanted values during multiple assignment, use the blank identifier _, which occupies no storage and does not collide with other identifiers.

package main

import "fmt"

var sharedValue = 15

func fetchDetails() (string, string) {
    personName := "BubbleDrink"
    groupTag   := "explorers"
    return personName, groupTag
}

func main() {
    localCounter := 5
    sharedValue := 150 // local shadowing
    fmt.Println(localCounter, sharedValue)
    _, tag := fetchDetails()
    fmt.Println(tag)
}

Key Rules

  • Outside functions, every statement must begin with a keyword (var, const, func, etc.).
  • The := syntax is invalid outside function scopes.
  • The blank identifier _ serves solely as a placeholder and does not allocate memory.

Tags: Go variable declaration programming language type inference short declaration

Posted on Mon, 25 May 2026 22:23:49 +0000 by supermars