Pythonista to Gopher: Navigating the Transition- Mastering Go’s Control Flow

Bestin Mathews
4 min readJun 19, 2024

--

As a seasoned Python developer, you’re familiar with the elegance and simplicity of Python’s control structures. Transitioning to Go might seem daunting at first, but fear not — Go’s control flow constructs are straight forward and intuitive once you get the hang of them. If you haven’t already, check out my blog on Getting started with Go!. It’s a fun dive into the world of Golang, and I’d love for you to give it a read..

In this post, we’ll explore how to navigate Go’s control structures, drawing parallels to Python’s syntax and highlighting the key differences. By the end of this, you’ll be equipped to handle conditionals, loops, and more with ease in Go. Let’s dive in!

Now, we’ll examine the control structures.

IF

In Go, the if-else control structure is similar to Python’s, but with a few key differences. Like Python, Go uses the if keyword to start the conditional statement, followed by a condition and a code block. However, Go uses curly braces {} to define the code block, whereas Python uses indentation. Additionally, Go does not have a dedicated elif keyword; instead, it uses the else if

Python

if x > 0:
print("x is positive")
elif x < 0:
print("x is negative")
else:
print("x is zero")

Go

if x > 0 {
fmt.Println("x is positive")
} else if x < 0 {
fmt.Println("x is negative")
} else {
fmt.Println("x is zero")
}

For Loops

In Python, you explicitly say “give me each item” with for item in collection. Where in Go, range takes care of fetching each item for you, focusing on the value within the loop. Python’s enumerate lets you access both the item’s value and its position (index) within the collection.Go’s range just gives you the value. But if you need the index, you can use a separate counter variable inside your Go loop.

Python

In Python, the for loop is known for its simplicity and flexibility. It can be used to iterate over a sequence (such as a list or a string) or to iterate over a range of numbers.

# A list of numbers.
numbers = [1, 2, 3, 4, 5]

# Print each number.
for number in numbers:
print(number)

# Print each number with its index.
for index, number in enumerate(numbers):
print(f"Number {index} is {number}")

Go

In Go, the for loop is similar but uses the range keyword to iterate over a sequence. It can also be used to iterate over a range of numbers.

package main

import "fmt"

func main() {
// A list of numbers.
numbers := []int{1, 2, 3, 4, 5}

// Print each number.
for _, number := range numbers {
fmt.Println(number)
}

// Print each number with its index.
for index, number := range numbers {
fmt.Printf("Number %d is %d\n", index, number)
}

// Print each number without its index.
for _, number := range numbers {
fmt.Printf("Number is %d\n", number)
}

}

While

While loops in Go are similar to Python’s while loops, but with a slightly different syntax. In Python, a while loop is defined using the while keyword followed by a condition and a colon, with the loop body indented. In Go, you can achieve the same functionality using a for loop in its simplest form. Instead of using a separate while keyword, Go uses the for keyword followed by the condition, and the loop body is enclosed in curly braces

Python

count = 0
while count < 5:
print(count)
count += 1

Go

count := 0
for count < 5 {
fmt.Println(count)
count++

Switch

Python’s switch statement, introduced in Python 3.10, provides a concise way to handle multiple conditional checks. It matches the value of an expression against a series of case statements, supporting various data types. This feature enhances code readability and maintainability, making it a valuable addition to the Python language.

Go’s switch statement is more concise and flexible compared to Python's switch statement. Go's switch allows for more complex conditions and supports multiple cases in a single switch block. Additionally, Go's switch does not require explicit break statements, unlike Python's switch which does. This makes Go's switch more efficient and easier to read. For example, in Go, you can write a switch statement that checks multiple conditions and executes different blocks of code based on the conditions. In contrast, Python's switch is more limited and requires explicit break statements to exit the switch block.

Python

def greet(name):
match name:
case "Tony":
print("Hello, Tony")
case "Stark":
print("Hello, Stark")
case _:
print("Hello, stranger!")

greet("Tony") # Output: Hello, Tony
greet("Stark") # Output: Hello, Stark
greet("Thanos") # Output: Hello, stranger!

Go

package main

import "fmt"

func greet(name string) {
switch name {
case "Tony":
fmt.Println("Hello, Tony")
case "Stark":
fmt.Println("Hello, Stark")
default:
fmt.Println("Hello, stranger!")
}
}

func main() {
greet("Tony") // Output: Hello, Tony
greet("Stark") // Output: Hello, Stark
greet("Thanos") // Output: Hello, stranger!
}

That’s it for this blog post on mastering Go’s control flow constructs. We’ve explored the similarities and differences between Go and Python’s control structures, from conditionals to loops and switch statements. By now, you should be well-equipped to handle the intricacies of Go’s control flow and transition smoothly from Python. Remember, practice makes perfect, so be sure to experiment with these constructs in your own Go projects. If you have any questions or need further clarification, feel free to reach out. In the next part of this series, we’ll dive deeper into Go’s data structures, including lists, dictionaries, maps, arrays, and more. Stay tuned for the next installment, where we’ll continue to explore the world of Go programming. Happy coding, and see you in the next one

--

--

Bestin Mathews
Bestin Mathews

Written by Bestin Mathews

In the mirror's truth and the cosmos embrace, I find my compass.

No responses yet