Introduction to Execution Paths
In structured programming, controlling the sequence of operations is fundamental. Go implements this through three core mechanisms: linear execution (sequential), decision-making (selection), and repetition (iterative). These constructs allow developers to manage program state and logic flow efficiently.
Conditional Execution
The if Statement
The foundation of decision-making in Go involves the if keyword. Similar to many other languages, it evaluates a boolean expression to determine whether a block of code should execute.
package main
import "fmt"
func main() {
// Initialize a numeric value
val := 45
// Evaluate the condition
if val > 20 {
fmt.Println("Value exceeds twenty")
}
if val > 50 {
fmt.Println("Value exceeds fifty")
}
}
Handling Alternatives with else
When multiple outcomes are possible, the else clause provides a fallback path when the initial condition fails.
package main
import "fmt"
func main() {
var result float64 = 85.5
// Assess the pass/fail threshold
if result >= 90.0 {
fmt.Println("Status: Passed")
} else {
fmt.Println("Status: Failed")
}
}
Nested Conditions
While Go allows an else if style syntax, complex logic often benefits from nesting if blocks to verify multiple independent criteria sequentially.
package main
import "fmt"
func main() {
var enteredPass, confirmedPass, secretPass int
secretPass = 998877
fmt.Print("Enter your PIN: ")
fmt.Scanln(&enteredPass)
if enteredPass == secretPass {
fmt.Println("Verification step two: Please re-enter.")
fmt.Scanln(&confirmedPass)
if confirmedPass == secretPass {
fmt.Println("Access granted successfully.")
} else {
fmt.Println("Mismatches detected.")
}
} else {
fmt.Println("Initial authentication failed.")
}
}
The switch Construct
The switch statement offers a cleaner alternative to chained if-else blocks when comparing a single expression against various constants. A key distinction in Go is that each case block automatically terminates upon completion, eliminating the explicit need for a break statement at the end of every branch.
package main
import "fmt"
func main() {
var mark int = 75
switch mark {
case 90:
fmt.Println("Grade: A")
case 80:
fmt.Println("Grade: B")
// Matching against multiple values
case 70, 50, 60:
fmt.Println("Grade: C")
default:
fmt.Println("Grade: D")
}
}
Furthermore, Go permits switch statements without an associated expression. In this scenario, conditions are treated as standalone boolean expressions evaluated top-down.
package main
import "fmt"
func main() {
var level int
fmt.Println("Input priority level:")
fmt.Scanln(&level)
switch {
case level > 90:
fmt.Println("Priority: Platinum")
case level >= 80 && level <= 90:
fmt.Println("Priority: Gold")
case level >= 60 && level < 80:
fmt.Println("Priority: Silver")
default:
fmt.Println("Level out of bounds")
}
}
Explicit Flow Transfer with fallthrough
By default, once a matching case is found, execution stops after that block. To force execution into subsequent cases regardless of their boolean validity, the fallthrough keyword is used. This bypasses the condition check for the following case.
package main
import "fmt"
func main() {
flag := false
switch flag {
case false:
fmt.Println("Case matched: False")
fallthrough // Force entry into next block
case true:
fmt.Println("Case matched: True")
}
}
To mitigate unintended cascading logic, explicit break commands can be inserted within fallthrough paths to stop further procesing immediately.
package main
import "fmt"
func main() {
isActive := false
switch isActive {
case false:
fmt.Println("State: Inactive")
fallthrough
case true:
if !isActive {
break // Terminate execution path manually
}
fmt.Println("State: Active")
case false:
fmt.Println("Reset State")
}
}
Iterative Structures
Using the for Loop
Although Go lacks dedicated while keywords, its for loop serves all purposes of iteration. It follows the standard pattern: initialization, condition evaluation, and post-operation update. Loop termination is managed via break (exits entirely) or continue (skips remaining loop body and proceeds to next iteration).
package main
import "fmt"
func main() {
var total int = 0
// Initialization; Condition; Update
for i := 0; i <= 10; i++ {
total += i
}
fmt.Println("Cumulative Total:", total)
}