...

/

Highlights from the Previous Chapters

Highlights from the Previous Chapters

We often refer to the full explanation and examples in previous chapters. Here, each section summarizes all the concepts learned in this course and warns what not to do!

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 accumulate string content, like in the following snippet:

var b
...