Go
Beginner
1 min read
Variable Declaration and Zero Values
Example
package main
import "fmt"
func main() {
// Explicit type with var
var age int = 30
var name string = "Alice"
// Type inferred with var
var pi = 3.14159
// Short declaration (most common inside functions)
city := "New York"
// Multiple variables at once
var x, y int = 10, 20
// Zero values
var zeroInt int
var zeroBool bool
var zeroString string
fmt.Println(age, name, pi, city)
fmt.Println(x, y)
fmt.Printf("Zero int=%d bool=%t string=%q\n", zeroInt, zeroBool, zeroString)
// Swap without a temp variable
a, b := 1, 2
fmt.Printf("Before swap: a=%d b=%d\n", a, b)
a, b = b, a
fmt.Printf("After swap: a=%d b=%d\n", a, b)
// Constants
const maxRetries = 5
const greeting = "Hello"
fmt.Println(greeting, maxRetries)
}