Skip to content

Learning Go book's highlights

Posted on:January 18, 2022 at 11:11 PM

Tl;dr

Learning Go

is a great book to learn about Go in general from the basics to advanced concepts such as: testing, cgo , concurrency, and even type parameters (aka generics) among others. I personally recommend this book for both experienced and novice Go developers, Jon Bodner made a great work explaining all the topics.

Extra resources you should read

Highlights

Write your programs in a way that makes your intentions clear.

There is one limitation on :=. If you are declaring a variable at package level, you must use var because := is not legal outside of functions.

When initializing a variable to its zero value, use var x int. This makes it clear that the zero value is intended.

As a general rule, you should only declare variables in the package block that are effectively immutable.

Avoid declaring variables outside of functions because they complicate data flow analysis.

Another Go requirement is that every declared local variable must be read. It is a compile-time error to declare a local variable and to not read its value.

If you find it hard to keep track of your short-named variables, it’s likely that your block of code is doing too much.

The type of a function is built out of the keyword func and the types of the parameters and return values. This combination is called the signature of the function.

Error handling is what separates the professionals from the amateurs.

Functions declared inside of functions are special; they are closures.

Any time your logic depends on values that are configured at startup or changed while your program is running, those values should be stored in a struct and that logic should be implemented as a method. If your logic only depends on the input parameters, then it should be a function.

It may seem ironic that a language as focused on readability as Go would borrow a concept from a language that is concise to a fault, but this is why you should learn many different programming languages: you can find inspiration everywhere.

You’ll often hear experienced Go developers say that your code should “Accept interfaces, return structs.”

If you want to create a new error that contains the message from another error, but don’t want to wrap it, use fmt.Errorf to create an error, but use the %v verb instead of %w.

The select algorithm is simple: it picks randomly from any of its cases that can go forward; order is unimportant. This is very different from a switch statement, which always chooses the first case that resolves to true.

Idiomatic Go is a set of tools, practices, and patterns that makes it easier to maintain software across time and changing teams. That’s not to say the cultures around other languages don’t value maintainability; it just may not be their highest priority.