The `goto` Statement
Part of the Logic & Flow section of Coddy's GO journey — lesson 4 of 68.
The goto statement in Go allows you to transfer control directly to a labeled statement within the same function. While Go includes this feature, it's rarely used in modern Go programming because clearer control structures like loops and if statements are preferred.
To use goto, you first define a label by writing an identifier followed by a colon. Then you can jump to that label using goto followed by the label name.
func main() {
i := 0
start:
fmt.Println("Count:", i)
i++
if i < 3 {
goto start
}
fmt.Println("Done!")
}In this example, the program jumps back to the start label until the condition is no longer met. However, this same logic would be much clearer using a for loop. The goto statement can make code harder to read and maintain, which is why it's generally discouraged in favor of structured control flow.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyIn this challenge, you'll practice using the goto statement to create a simple retry mechanism. You're building a connection system that attempts to establish a connection and retries a specific number of times if it fails.
You will receive two inputs:
- A string representing the maximum number of retry attempts (e.g.,
"3") - A string representing the attempt number that will succeed (e.g.,
"2")
Your task is to:
- Parse the maximum retry attempts from the first input
- Parse the success attempt number from the second input
- Use a
gotostatement with a label to implement the retry logic - Start with attempt number 1 and increment after each failed attempt
- For each attempt that fails, print
"Attempt [attempt_number] failed" - When the attempt number matches the success attempt number, print
"Attempt [attempt_number] succeeded"and exit - If you exceed the maximum retry attempts without success, print
"All attempts failed"and exit
Use the goto statement to jump back to the retry label when an attempt fails and you haven't exceeded the maximum attempts. The attempt numbers should start from 1.
Cheat sheet
The goto statement transfers control directly to a labeled statement within the same function. Define a label with an identifier followed by a colon, then jump to it using goto:
func main() {
i := 0
start:
fmt.Println("Count:", i)
i++
if i < 3 {
goto start
}
fmt.Println("Done!")
}While goto is available in Go, it's rarely used in modern Go programming as structured control flow like loops and if statements are clearer and more maintainable.
Try it yourself
package main
import (
"fmt"
"strconv"
)
func main() {
// Read input
var maxRetriesStr string
var successAttemptStr string
fmt.Scanln(&maxRetriesStr)
fmt.Scanln(&successAttemptStr)
// Parse inputs to integers
maxRetries, _ := strconv.Atoi(maxRetriesStr)
successAttempt, _ := strconv.Atoi(successAttemptStr)
// Initialize attempt counter
attempt := 1
// TODO: Write your code below
// Use goto statement with a label to implement retry logic
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Control Flow
Switch with `fallthrough`Breaking from Nested LoopsContinuing a Specific LoopThe `goto` StatementRecap - Advanced Loop Control4Project: Simple Task List
Project SetupAdding a Task2Structs and Methods
Defining Methods on StructsValue ReceiversPointer ReceiversChoosing ReceiversMethods vs FunctionsRecap - Struct Behavior5Maps In-Depth
Maps of StructsPointers as Map ValuesTesting for Nil MapsComparing MapsRecap - Word Frequency Counter3Interfaces (The Basics)
What is an Interface?Defining an InterfaceImplementing an InterfaceUsing Interface TypesEmpty InterfaceType AssertionsType SwitchRecap - Shapes and Behaviors