Go — Variables & Constants in Go

🐹 Go 1.22+ 🟢 Lesson 6 of 48 📂 Phase 03: Variables and Data Types 📅 2026 Edition
📌 Covered in this chapter: var keyword · Short declaration operator := · Zero values · Block scope vs Package scope · const keyword · iota enumerator

Welcome to Go — Variables & Constants in Go in our Go Complete Masterclass! Declare variables and constants in Go using var keywords or short := inferencing, zero values, package scope, and constant pools.

1Variables & Declarations in Go

Go lo variables define cheyyadaniki 2 main forms unnayi: standard var keyword mariyu Short Declaration Operator :=.

Syntax FormExample CodeScope & Usage
Explicit var Declarationvar age int = 25Package level (global) or function level. Type explicitly specified.
Inferred var Declarationvar name = "Ramesh"Go compiler automatically infers type (string).
Short Declaration (:=)score := 98.5Function scope ONLY! Cannot be used at package level. Declares & initializes.
Multiple Declarationsvar x, y int = 10, 20 or a, b := 1, "hi"Multiple variables declared in a single clean line.
⚡ Zero Values in Go (No Garbage Memory!)

In languages like C, uninitialized variables contain random garbage data from RAM. In Go, every variable declared without an explicit initial value is automatically assigned its Zero Value:

  • int / float: 0 / 0.0
  • bool: false
  • string: "" (empty string)
  • pointers / slices / maps / channels / interfaces: nil
2Constants & The iota Enumerator

Constants in Go are declared using the const keyword. Constant values must be known at compile-time.

Go — iota Enumerator Pattern ▶ Run Code
package main

import "fmt"

const (
    StatusPending  = iota // 0
    StatusActive          // 1
    StatusApproved        // 2
    StatusRejected        // 3
)

const (
    _  = iota             // Ignore zero
    KB = 1 << (10 * iota) // 1 << 10 = 1024
    MB                    // 1 << 20 = 1048576
    GB                    // 1 << 30 = 1073741824
)

func main() {
    fmt.Println("Pending:", StatusPending, "Approved:", StatusApproved)
    fmt.Printf("1 MB = %d Bytes, 1 GB = %d Bytes\n", MB, GB)
}
💻 Live Go Code Execution

Test and run this Go program in our online high-performance Go compiler environment:

Open in Online Go Compiler →
OC
Written by Our Compiler Technical Editorial Team
Reviewed for accuracy & tested on Go 1.22+ · Last updated August 2026