Go•Maps
Go Maps: Key-Value Hash Tables and the Comma-Ok Idiom
Go maps provide O(1) hash table lookups. The comma-ok idiom verifies key existence without default zero values.
Syntax
m := make(map[string]int)
val, ok := m["key"]
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| val, ok := map[key] | Comma-Ok Idiom | ok is a boolean indicating whether key exists in map. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing Go locally:
package main
import "fmt"
func main() {
portRegistry := map[string]int{
"HTTP": 80,
"HTTPS": 443,
"SSH": 22,
}
portRegistry["REDIS"] = 6379
// Comma-ok idiom to test key existence
port, exists := portRegistry["HTTPS"]
fmt.Printf("HTTPS Port: %d (Exists: %t)\n", port, exists)
missingPort, exists := portRegistry["UNKNOWN"]
fmt.Printf("UNKNOWN Port: %d (Exists: %t)\n", missingPort, exists)
// Deleting key
delete(portRegistry, "SSH")
fmt.Printf("Total Registered: %d ports\n", len(portRegistry))
}Expected Output:
HTTPS Port: 443 (Exists: true) UNKNOWN Port: 0 (Exists: false) Total Registered: 3 ports
How It Works: Step-by-Step
- Lines 6-10: Initializes map literal with protocol strings and port numbers.
- Lines 15-19: Comma-ok idiom checks existence (returns false for "UNKNOWN").
- Line 22: delete(map, key) removes entry.
Key Concepts
- Reading a missing key in Go returns the type zero value (e.g. 0 for int).
- The comma-ok idiom val, ok := m[k] distinguishes between a key storing 0 and a missing key.
- Maps are reference types; passing a map to a function allows the function to mutate it.
Common Mistake: Writing to a nil map before initializing with make()
Writing to a nil map (var m map[string]int) causes a runtime panic. Always use make() or map literal.
❌ Incorrect
var m map[string]int m["a"] = 1 // Panic: assignment to entry in nil map!
✅ Correct
m := make(map[string]int) m["a"] = 1
Related Go Tutorials & Compiler
Go Slices: append, make, copy, and Slicing Operations
Master dynamic slices in Go with make, append, copy, length, and capacity.
Go Structs: Fields, Tags, and Custom Types
Define structured records in Go with typed fields and field tags.
Go Strings, Runes, and the strings Package
Understand UTF-8 encoded strings, runes (Unicode code points), and strings package functions.
Go Online Compiler
Open in Compilra IDE
Run and test Go on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.