10 things I learnt about Go

Alex Tan
2 min readSep 9, 2017

1. There’s no round function for numbers

If you want to round numbers in go, you have to implement it yourself, that is, until go 1.10 is released.

2. There’s no reverse string function

Again, it’s weird that go lacks something as simple as a reverse string function. But there are times when you actually need it. Here's how you can do it:

3. Writing to a JSON file

Marshalling is the process of converting domain objects to a serialized format, such as json. In order to write a golang struct to a json file, you need to marshal it first:

If you set pretty to true, it will be saved in a more readable format. This is how our output json will look like:

4. Loading a JSON file

Unmarshalling is the process of converting domain objects from a serialized format, such as json. To load the json file to our golang struct, we have to unmarshal the json data:


This is the json file we are loading:

5. Mapping map to structs

In case you need to map golang map to structs, there is a library for it:

6. Shadowing fields

There are times where you want to hide certain fields from the golang struct before returning it as a json response, but not with the json:"-" approach. The example below shows how you remove the password field from the original struct:

7. Composing struct

When returning a json response, you might want to return fields from other structs, but want to avoid creating too many of them. One way to achieve this is by composition - you compose a new struct by embedding other structs and you choose to exclude the fields too through shadowing (see previous example).

8. Overwriting tag names

The name of the fields returned in the json is based on the json tag in your struct. You can overwrite them if you want your json response to have different field name:

9. Concatenating arrays

It’s probably wasn’t that obvious, but concatenating array can be easily done as shown below:

Note that both arrays must be of the same type. Appending a string array to an int array will result in an error.

10. It’s fast

Here’s a benchmark of a “hello world” request using wrk. View the full report below:

1 threads and 1 connections:

Similar test carried out with 10 threads and 10 connections: