Go Variables
Understanding data storage in Go programming
📦 What are Go Variables?
Variables in Go are containers that store data values. They act like labeled boxes where you can keep different types of information like numbers, text, or boolean values for use in your programs.
// This is a simple Go variable example
var message string = "Hello, Go!"
var age int = 25
fmt.Println(message)
fmt.Println(age)
Output:
Hello, Go!
25
Key Variable Concepts
Variable Names
Identifiers to reference stored data
var username string
Data Types
Specify what kind of data to store
var count int = 10
Values
The actual data stored in variables
var price float64 = 19.99
Assignment
Giving values to variables
name := "Alice"
🔹 Basic Variable Types
Go has several built-in data types for variables:
// String variables
var name string = "John Doe"
// Integer variables
var age int = 30
// Float variables
var height float64 = 5.9
// Boolean variables
var isStudent bool = true
fmt.Println(name, age, height, isStudent)
Output:
John Doe 30 5.9 true
🔹 Variable Declaration Syntax
Go provides different ways to declare variables:
// Method 1: var keyword with type and value
var message string = "Hello"
// Method 2: var keyword with type (zero value)
var count int
// Method 3: var keyword with value (type inferred)
var price = 29.99
// Method 4: Short declaration (inside functions only)
city := "New York"
fmt.Println(message, count, price, city)
Output:
Hello 0 29.99 New York
🔹 Zero Values
Variables declared without initial values get zero values:
var text string // "" (empty string)
var number int // 0
var decimal float64 // 0.0
var flag bool // false
fmt.Printf("String: '%s'\n", text)
fmt.Printf("Integer: %d\n", number)
fmt.Printf("Float: %.1f\n", decimal)
fmt.Printf("Boolean: %t\n", flag)
Output:
String: ''
Integer: 0
Float: 0.0
Boolean: false