Search⌘ K
AI Features

Highlights from the Previous Chapters

Explore common pitfalls in Go such as variable shadowing, inefficient string handling, defer scope errors, pointer and interface misuse, and poor error handling. Understand how to avoid these issues and apply best practices for effective Go programming.

Hiding a variable by misusing short declaration

In the following code snippet:

var remember bool = false
if something {
  remember := true // Wrong.
}
// use remember

The variable remember will never become true outside of the if-body. Inside the if-body, a new remember variable that hides the outer remember is declared because of :=, and there it will be true. However, after the closing } of if, the variable remember regains its outer value false. So, write it as:

if something {
  remember = true
}

This can also occur with a for-loop, and can be particularly subtle in functions with named return variables, as the following snippet shows:

func shadow() (err error) {
  x, err := check1() // x is created; err is assigned to
  if err != nil {
    return // err correctly returned
  }
  if y, err := check2(x); err != nil { // y and inner err are created
    return // inner err shadows outer err so err is wrongly returned!
  } else {
    fmt.Println(y)
  }
  return
}

Misusing strings

When you need to do a lot of manipulations on a string, think about the fact that strings in Go (like in Java and C#) are immutable. String concatenations of the kind a += b are inefficient, mainly when performed inside a loop. They cause many reallocations and the copying of memory. Instead, one should use a bytes.Buffer to ...