How different languages handle the flow of execution, through conditional statements, loops and errors.
Control Flow
Go Control-Flow
Conditional Statements
Control the flow of execution based on conditions.
import "fmt" func checkNumber(num int) string { if num > 0 { return "Positive" } else if num < 0 { return "Negative" } else { return "Zero" } } func main() { fmt.Println(checkNumber(5)) // Positive fmt.Println(checkNumber(-3)) // Negative fmt.Println(checkNumber(0)) // Zero }
Error Loading
Missing
Ternary Operator or Select
A shorthand for conditional expressions.
Go does not have a ternary operator (? :
). Instead, we use if
expressions:
func main() { num := 5 var result string if num > 0 { result = "Positive" } else if num < 0 { result = "Negative" } else { result = "Zero" } fmt.Println(result) }
Missing
Switch / Case
A control structure for multi-way branching.
The switch
statement in Go allows you to execute different blocks of code based on the value of an expression. It is more flexible than in many other languages because it does not require explicit break
statements.
func getDayName(day int) string { switch day { case 0: return "Sunday" case 1: return "Monday" case 2: return "Tuesday" case 3: return "Wednesday" case 4: return "Thursday" case 5: return "Friday" case 6: return "Saturday" default: return "Invalid day" } }
You can group multiple cases together if they share the same logic.
func isWeekend(day int) string { switch day { case 0, 6: // Sunday or Saturday return "It's the weekend!" default: return "It's a weekday." } }
In Go, you can use a switch
statement without an expression, which acts like a series of if
/else
conditions.
func checkNumber(num int) string { switch { case num > 0: return "Positive" case num < 0: return "Negative" default: return "Zero" } }
Missing
Loop Over - Iterables
Iterate over elements in a collection or iterable.
Go supports multiple loop constructs.
Basic for
loop
func main() { for i := 0; i < 5; i++ { fmt.Println(i) } }
Range-based iteration (for range
)
func main() { numbers := []int{1, 2, 3} for _, num := range numbers { fmt.Println(num) } }
Iterating Over a Map (Equivalent of for...in
)
func main() { user := map[string]string{"id": "1", "name": "Alice"} for key, value := range user { fmt.Printf("%s: %s\n", key, value) } }
Missing
Loop Conditional Exit
Exit a loop based on a condition.
Go allows breaking out of loops based on conditions and also supports do...while
-like behavior using for
.
Basic for
with condition (Equivalent of do...while
)
func main() { i := 0 for { fmt.Println(i) i++ if i >= 5 { break // Exit loop } } }
Breaking out of a loop
func main() { for i := 0; i < 10; i++ { if i == 5 { break // Exit loop when i equals 5 } fmt.Println(i) } }
Using continue
to skip iterations
func main() { for i := 0; i < 10; i++ { if i%2 == 0 { continue // Skip even numbers } fmt.Println(i) } }
Missing
Co-Routine - Yield
Pause and resume execution at specific points.
Go does not support native coroutines or yield
, but goroutines and channels provide similar behavior for asynchronous execution.
Using a Goroutine for Lazy Evaluation
func generator(ch chan int) { for i := 1; i <= 3; i++ { ch <- i // Send value to channel time.Sleep(time.Second) } close(ch) // Close the channel when done } func main() { ch := make(chan int) go generator(ch) for num := range ch { // Reads from the channel until closed fmt.Println(num) } }
Infinite Counter with Goroutines (Lazy Iteration)
import ( "fmt" "time" ) func counter(ch chan int) { i := 0 for { ch <- i // Send value i++ time.Sleep(time.Second) // Simulate work } } func main() { ch := make(chan int) go counter(ch) fmt.Println(<-ch) // 0 fmt.Println(<-ch) // 1 fmt.Println(<-ch) // 2 }
Goroutines + Channels provide a coroutine-like mechanism in Go, allowing controlled iteration with lazy execution.
Missing
Exceptions
Handle errors or exceptional conditions in a structured way.
Go does not have exceptions like many other programming languages (e.g., try
/catch
blocks). Instead, Go uses error values to handle errors explicitly. This approach encourages developers to handle errors at every step, making the code more predictable and robust. Basic Error Handling:
In Go, functions often return an error
as the second return value to indicate if something went wrong.
import ( "errors" "fmt" ) func divide(a, b int) (int, error) { if b == 0 { return 0, errors.New("division by zero") } return a / b, nil } func main() { result, err := divide(10, 0) if err != nil { fmt.Println("Error:", err) } else { fmt.Println("Result:", result) } }
Using panic
and recover
: - Go provides panic
and recover
for handling unexpected errors. However, these are typically used for unrecoverable errors or debugging purposes, not for general error handling.
panic
: Stops the normal execution of a program and begins unwinding the stack.recover
: Allows you to regain control of a panicking program.
import "fmt" func riskyFunction() { defer func() { if r := recover(); r != nil { fmt.Println("Recovered from panic:", r) } }() panic("Something went wrong!") } func main() { fmt.Println("Before risky function") riskyFunction() fmt.Println("After risky function") }
Best Practices for Error Handling in Go: -
-
Return Errors Explicitly:
- Always return errors as part of the function's return values.
- Check for errors immediately after calling a function.
-
Use
panic
for Truly Exceptional Cases:- Reserve
panic
for situations where the program cannot continue (e.g., corrupted state, missing critical resources).
- Reserve
-
Wrap Errors for Context:
- Use the
fmt.Errorf
function to add context to errors.
- Use the
import ( "fmt" "os" ) func readFile(filename string) error { _, err := os.Open(filename) if err != nil { return fmt.Errorf("failed to open file %s: %w", filename, err) } return nil } func main() { err := readFile("nonexistent.txt") if err != nil { fmt.Println("Error:", err) } }