Skip to main content

Command Palette

Search for a command to run...

Navigating From Python and JavaScript to Go: Loops and Errors

Published
4 min read
Navigating From Python and JavaScript to Go: Loops and Errors

The Jump to Go

I recently started learning the Go language as part of the Boot.Dev Back-end Career Path. Up until now, most concepts have been similar and relatively easy to grasp. However, diving into loops and errors, I've begun to find fundamental differences in philosophy. Go's approach to iteration and error handling represents a clear shift in mindset from scripting languages like Python and JavaScript.

The Power of One: Go's Singular for Loop

In Python and JavaScript, we rely on multiple keywords—like for, while, and sometimes do-while—to handle different kinds of iteration. Go simplifies this entire landscape by relying on a single, powerful for keyword.

Python and JavaScript Context

In traditional scripting languages, the syntax changes based on the type of loop you need.

In Python, the for keyword is primarily used for iterating through collections (like strings or lists): Python

Looping through a string

for x in "python":
  print(x)

In JavaScript, you often use the verbose C-style for loop for indexed iteration:

const colors = ["red", "green", "blue"];
let len = colors.length;
let text = "";

for (let i = 0; i < len; i++) {
  text += colors[i];
}

Both languages also rely on a separate while keyword to execute a loop as long as a condition is true: Python

The while loop

In Python:

i = 2
while i <= 6:
  print(i)
  i += 1

In JavaScript:

let j = 1;
let text = "";
while (j < 6) {
  text += "The result is " + j;
  j++;
}

Go's Simplicity

Go has a single, powerful for keyword that performs the job of all those other loops. The basic loop in Go is written in standard C-like syntax:

The Traditional Iterative for Loop:

Here is a simple for loop in Go:

for i := 0; i < 20; i++ {
  fmt.Println(i) // Prints 0 through 19
}

Note for Python/JS users: Notice that there are no parentheses in the above example. The parentheses around the condition are not required in Go.

The Go 'While' Loop (Condition-Only for):

Because Go allows us to omit sections of a for loop, we create the equivalent of a while loop by only providing the condition section.

For example:


i := 1
for i < 100 { // No initial or increment statement needed
  i++
}

The Infinite Loop:

You can create an infinite loop by simply omitting all sections: for {}. This is typically used in server applications or combined with continue and break to manage control flow.

Control Flow Keywords:

In Go, the keywords continue and break are used to change the control flow of a loop.

continue: stops the current iteration and moves on to the next.

break: stops the current iteration and exits the loop entirely.


// Example using continue:
for i := 0; i < 10; i++ {
  if i % 2 == 0 {
    continue // Skip even numbers
  }
  fmt.Println(i) // Prints: 1, 3, 5, 7, 9
}

    // Example using break:
    for i := 0; i < 10; i++ {
      if i == 5 {
        break // Exit the loop when i is 5
      }
      fmt.Println(i) // Prints: 0, 1, 2, 3, 4
    }

The Go Way: Explicit Error Handling

A Shift in Philosophy

Go's approach—explicit return values—is very different from Python/JS's common use of exceptions and try...catch blocks. Go views errors not as something exceptional that halts execution, but as expected values that must be handled.

The error Type:

Errors in Go are simply values which implement the built-in error interface, not hidden exceptions that jump up the call stack. A function that might fail will typically return two values: the expected result and an error.

Example: Go func divide(numerator float64, denominator float64) (float64, error) { if denominator == 0 { return 0, errors.New("cannot divide by zero") } return numerator / denominator, nil }

The Idiomatic Check:

In the example above, we see the standard if err != nil pattern. This is crucial because the pattern forces the developer to acknowledge and handle every potential error immediately, leading to robust and explicit code. You can't ignore errors in Go; you must decide what to do with them.

Creating Errors:

We can use errors.New or fmt.Errorf for creating simple, custom errors. The errors.New function returns a distinct error value containing the given text.


    package main

    import (
      "errors"
      "fmt"
    )
    func main() {
      err := errors.New("This is an example error: You did something wrong!")
      if err != nil {
        fmt.Println(err)
      }
    }

My Biggest Takeaways

Go's single for keyword offers impressive versatility, and its error handling is a model of explicitness. I find that these features make the language feel much clearer, cutting out some of the verbosity and jargon seen in other places. I'm not saying Python or JavaScript are overly verbose, but Go's philosophy—especially its focus on readability and directness—aligns closely with my personal tastes right now.