A lot of the open source infrastructure tooling that I use is written in Golang, and I wanted to understand how it worked,
So a few months ago, I decided to teach myself some Golang.
After writing some Golang code for a few side projects, I decided to take a step back, and list down the things that have made me love Golang.

Interfaces

Interfaces in Go are implemented implicitly.
One of the things that I like about Golang interfaces is that they can be added after the fact.
If you add a new interface, there’s no need to modify existing types to make them implement that interface.

Dependency Injection

Golang interfaces can be used for dependency injection,
In Go functions can take interfaces as arguments, this means that we can decouple the function from it’s dependency.
This allows us to call the function, even when it’s dependency is not available.

For eg;
We have a function GetUserIdByEmail which, when given an email id, queries a Redis datastore, and returns the user id mapped against that user.

1
2
3
4
func GetUserIdByEmail(ds DataStore, email string) string {
key := "user_" + email + "_uid"
return ds.Get(key)
}

The interface DataStore is defined here:

1
2
3
4
5
type DataStore interface {
Get(string) string
Set(string, string)
Del(string)
}

In our program, when the our Redis datastore exists, the function GetUserIdByEmail works fine, but what if we need to use test this function? Is it possible to do so without using a datastore?

Yes, in this case we can create our own type that has three methods:

  • Get(string) string
  • Set(string, string)
  • Del(string)

We can then pass this as argument to the GetUserIdByEmail function and test it’s behaviour.
This allows us to easily test our code and support multiple datastores with ease.

CSP style concurrency

Go allows writing concurrent programs, and this is done by using goroutines,
A goroutine is a lightweight green thread that allows us to run code concurrently. Resource allocation & scheduling is handled by the go runtime, and we can spin up millions of goroutines, without running into any issues.

These goroutines communicate to each other using channels (as opposed to sharing memory).
This is much easier to manage than having multiple threads have shared memory (which can have a data race, if not synchronized properly)

Beginner friendly resources, simple syntax and excellent tooling

One of the things I like about Golang, is it’s simple syntax.
Finding resources to learn Golang was very easy. There were tons of tutorials, the IDE extensions worked straight out of the box.
Go also comes with test/benchmark/coverage tools (go test), a code formatter (go fmt) and a code analyzer (go vet)