5 Useful Go Tricks and Tips You Should Know 🐹 🚀

Carlos García Rosales
2 min readNov 9, 2021

Versión en Español

Go is one of the most useful language for different task specially for concurrency tasks and because all native libraries this language have with a lot of common functions we need every day.

Today I will show you 5 of this tricks I use in my day as a Go remote programmer.

1. Execution time of a code

It’s very common use Go because the amazing performance of this language have, so one of the things I do every day is measure the execution time of my code in Go. You can use a function and add it in the defer statement for improve the readability.

2. Marshall Json string with no defined Struct to a “Object”

This is a common problem in a Log system when we save a Response and Request with not defined struct and we need to manipulate information inside of this strings.

3. Get Test Coverage of your code

You can check the test coverage of your project in a nice interface in the browser and verify what parts of your code need to be test.

go test -coverprofile=coverage.out ./… && go tool cover -html=coverage.out && rm coverage.out

Your code not tested will appear in Red color and you code tested in green color.

4. Search if a String is inside of a Slice

Another common problem its a simple search problem of a string in a slice for example I wanna make a list about fields are permitted to be modified in a endpoint. The search method will depend of the array size in my case is a very short arrays so I use a simple search.

5. CPU Profiling

Also one of my favorites tools in Go is the CPU profiling tool for get a most extensive analysis of your code performance.

go test -cpuprofile=cpu.out ./… && go tool pprof cpu.out && rm cpu.out

--

--

Carlos García Rosales

I am Software Developer working in @bayonet.io using the amazing programming language Go! I hope help you with my articles. follow me in my social medias!