Go — Variables & Constants in Go
📌 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 Form | Example Code | Scope & Usage |
|---|---|---|
| Explicit var Declaration | var age int = 25 | Package level (global) or function level. Type explicitly specified. |
| Inferred var Declaration | var name = "Ramesh" | Go compiler automatically infers type (string). |
| Short Declaration (:=) | score := 98.5 | Function scope ONLY! Cannot be used at package level. Declares & initializes. |
| Multiple Declarations | var 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.0bool:falsestring:""(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 →