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/opReading Results:
10000000: iterations run136 ns/op: nanoseconds per operation
Memory Analysis #
Add memory statistics with -benchmem:
go test -bench=. -benchmemShows:
B/op: bytes allocated per operationallocs/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 + initializevardeclaration+=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.