Day 2 — Variables, Types & Zero Values
Learning Objectives
- Understand Go's static type system and why it prevents bugs
- Use
constwithiotafor typed enumerations - Know what zero values are and why they matter for network buffers
Key Concepts
// var declaration (explicit type)
var name string = "proxy"
var port int = 8080
// Short declaration (inferred type, only inside functions)
host := "localhost"
timeout := 30 * time.Second
// Constants — evaluated at compile time
const maxConnections = 10_000
// iota — auto-incrementing constant generator
type Protocol int
const (
TCP Protocol = iota // 0
UDP // 1
TLS // 2
HTTP // 3
)
Zero values — every variable is initialized to its zero value. Critical for networking:
| Type | Zero value | Networking implication |
|---|---|---|
int |
0 |
Safe default for counters |
bool |
false |
Feature flags default off |
string |
"" |
Empty host means "not set" |
[]byte |
nil |
Nil slice ≠ empty slice |
*T |
nil |
Nil pointer — always check |
Exercise: Network Unit Converter
package main
import "fmt"
type ByteUnit int64
const (
Byte ByteUnit = 1
Kilobyte ByteUnit = 1024
Megabyte ByteUnit = 1024 * 1024
Gigabyte ByteUnit = 1024 * 1024 * 1024
)
type DurationUnit int64
const (
Millisecond DurationUnit = 1
Second DurationUnit = 1000
Minute DurationUnit = 60 * 1000
)
func convertBytes(value int64, from, to ByteUnit) float64 {
return float64(value) * float64(from) / float64(to)
}
func main() {
fmt.Printf("1 GB = %.0f MB\n", convertBytes(1, Gigabyte, Megabyte))
fmt.Printf("512 MB = %.2f GB\n", convertBytes(512, Megabyte, Gigabyte))
fmt.Printf("100 Mbps link: %.0f KB/s max throughput\n",
convertBytes(100*1_000_000/8, Byte, Kilobyte))
}
Real-World Context
When your team sets MaxRequestBodySize = 10MB, that's ByteUnit math. When you configure IdleConnTimeout = 90 * time.Second, that's duration constants. Typed constants prevent the 10 * 1024 * 1024 scattered everywhere.