Skip to main content
Go: Iteration and Loops
  1. Posts/

Go: Iteration and Loops

·331 words·2 mins·
Roman
Author
Roman
Photographer with MSci in Computer Science and a Home Lab obsession
Table of Contents

Following the Learn Go with Tests guide.

For Loop Variations
#

Go has only one looping construct: for. Here are the different ways to use it:

Classic Three-Component Loop
#

for i := 0; i < 5; i++ {
    fmt.Println(i)
}

While-Style Loop
#

i := 1
for i <= 3 {
    fmt.Println(i)
    i++
}

Infinite Loop
#

for {
    fmt.Println("loop")
    break // exit condition
}

Range Over Integer
#

for i := range 3 {
    fmt.Println("range", i) // prints 0, 1, 2
}

Continue and Break
#

for n := range 6 {
    if n%2 == 0 {
        continue // skip even numbers
    }
    fmt.Println(n) // prints 1, 3, 5
}

  • No parentheses around conditions
  • Braces {} always required

Benchmarking
#

Go includes built-in benchmarking in the testing framework:

func BenchmarkRepeat(b *testing.B) {
	// setup
	for b.Loop() {
		Repeat("a") // code to measure
	}
	// cleanup
}

Run benchmarks with:

go test -bench=.

Example output:

10000000    136 ns/op

Reading Results:

  • 10000000: iterations run
  • 136 ns/op: nanoseconds per operation

Memory Analysis
#

Add memory statistics with -benchmem:

go test -bench=. -benchmem

Shows:

  • B/op: bytes allocated per operation
  • allocs/op: memory allocations per operation

String Concatenation Performance
#

Strings in Go are immutable. Each concatenation creates a new string, which impacts performance:

// Inefficient for multiple concatenations
func Repeat(character string) string {
	var repeated string  // var declares without initializing
	for i := 0; i < 5; i++ {
		repeated += character // += adds right to left and assigns back
	}
	return repeated
}

Go Operators:

  • := shorthand for declare + initialize
  • var declaration
  • += adds right operand to left and assigns result back

Using strings.Builder
#

For better performance with multiple concatenations:

func Repeat(character string) string {
	var repeated strings.Builder
	for i := 0; i < 5; i++ {
		repeated.WriteString(character)
	}
	return repeated.String()
}

strings.Builder benefits:

  • Minimizes memory copying
  • More efficient for repeated concatenations
  • Reduces memory allocations

Explore the Standard Library: Study the strings package for many useful string manipulation functions.