5 Lesser-Known Go Keywords to Level Up Your Code
5 Lesser-Known Go Keywords to Level Up Your Code
Think you've seen it all in Go? From for
loops to if
statements, Go's standard fare is familiar... but there's a handful of keywords and concepts that can supercharge your code. In this post, we'll dive into 5 neat (and slightly underappreciated) Go features: iota
, new
, labeled loops, goto
, and the blank identifier _
. Expect code samples, a sprinkle of humor, and practical tips for each. Ready? Let's roll!
1. iota: Automatic Constant Sequencer
Tired of manually assigning incrementing constants?
Bad approach:
goconst ( Monday = 0 Tuesday = 1 Wednesday = 2 Thursday = 3 Friday = 4 Saturday = 5 Sunday = 6 )
Better with iota
:
goconst ( Monday = iota // 0 Tuesday // 1 Wednesday // 2 Thursday // 3 Friday // 4 Saturday // 5 Sunday // 6 )
Want weekdays starting at 1? Just add an expression:
goconst ( Monday = iota + 1 // 1 Tuesday // 2 Sunday // 7 )
Skip a value with an underscore:
goconst ( _ = iota // ignore 0 Monday // 1 Tuesday // 2 // ... )
Bit flags? Also easy:
goconst ( Readable = 1 << iota // 1 << 0 = 1 Writable // 1 << 1 = 2 Executable // 1 << 2 = 4 )
2. new: On-Demand Zeroed Memory
new(T)
allocates zeroed memory and returns *T
. You don’t have to set fields to their zero values.
gotype Counter struct { Count int } func NewCounter() *Counter { return new(Counter) } func (c *Counter) Inc() { c.Count++ } func main() { ctr := NewCounter() ctr.Inc() fmt.Println(ctr.Count) // 1 }
No surprises: new(Counter)
gives you a *Counter
with Count == 0
.
3. Labeled Loops: Breaking Out of the Matrix
Want to break out of nested loops in one shot? Labels to the rescue:
goOuter: for i := 0; i < 3; i++ { for j := 0; j < 3; j++ { if i*j > 1 { break Outer } fmt.Println(i, j) } }
Once i*j > 1
, we jump straight out of both loops.
4. goto: When You Need a Quantum Leap
goto
can sometimes simplify state machines or performance-critical paths:
gofor i := 0; i < 5; i++ { if i == 3 { goto SkipPrint } fmt.Println("i is", i) } SkipPrint: fmt.Println("Loop ended via goto")
Use sparingly, but it’s a handy "bolt-cutters" tool in tight spots.
5. Blank Identifier (_): The Ultimate Trash Bin
Ignore any return value you don’t need:
gofunc fetch() ([]int, error) { return []int{1,2,3}, nil } func main() { nums, _ := fetch() // we know err is nil for now for _, n := range nums { fmt.Println(n) } }
Even import solely for side-effects:
goimport ( "fmt" _ "github.com/lib/pq" // init DB driver )
That’s a wrap! Five small Go features, big potential impact. Try them out, and for a free 15-minute Go crash course, check out this video: Go Crash Course.
Happy coding! 🚀