Go (or Golang, if you want to impress your nerdy friends) has three powerful control flow tools: break
, continue
, and goto
. These keywords help your loops and logic behave exactly as you want—whether that means stopping in your tracks, skipping ahead, or teleporting to a specific point in your code like a sci-fi time traveler.
break
- The Emergency Exit
The break
statement is like pulling the fire alarm—it immediately stops execution of the nearest loop and sends you packing.
Example:
for i := 1; i <= 5; i++ {
if i == 3 {
break // Stop the loop when i is 3
}
fmt.Println("Iteration:", i)
}
Output:
Iteration: 1
Iteration: 2
When i
equals 3, we say, “Nope, I’m out,” and exit the loop.
continue
- The Skip Button
The continue
statement is like fast-forwarding—rather than stopping the loop, it skips to the next iteration.
Example:
for i := 1; i <= 5; i++ {
if i == 3 {
continue // Skip the rest of this iteration when i is 3
}
fmt.Println("Iteration:", i)
}
Output:
Iteration: 1
Iteration: 2
Iteration: 4
Iteration: 5
When i
equals 3, Go says, “Nah, let’s just move on.”
goto
- The Teleporter
The goto
statement is like having a warp portal in your code—it lets you jump to a specific label instantly. But be careful, excessive use can turn your code into a spaghetti mess!
Example:
var i int = 1
start:
if i > 5 {
return
}
fmt.Println("Iteration:", i)
i++
goto start // Jump back to the start label
Output:
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
Go sees goto start
and teleports execution back to the label named start
. It's fun, but use it wisely!
When to Use What?
Statement | Use Case |
---|---|
break |
When you want to exit a loop immediately. |
continue |
When you want to skip an iteration but keep looping. |
goto |
When you need to jump to a specific point (rarely recommended). |
break
, continue
, and goto
are essential tools in Go. break
stops everything, continue
skips ahead, and goto
lets you teleport (but don’t abuse it!). Master these, and your loops will be under your full control. Happy coding!
0 Comments