Some uncommon Go flags I found interesting

January 20, 2024

These are some of the Go compiler flags which I found interesting when I discovered them.

Thought I will write them down so I don’t forget them.

Disabling function inlining when debugging objdumps

-l will disable inlining (but still retain other compiler optimisations). This is very useful if you are investigating small methods, but can’t find them in objdump.

Sample command: go build -gcflags="-l" main.go

Disable all optimizations by Go

-gcflags="-N" will disable all optimizations done by the Go compiler. But why would you disable the optimizations? Well, you should definitely not disable in production builds but if you have to debug complex concurrency bugs or memory corruption then disabling optimizations can make debugging more predictable.

Or maybe just to profile your code to see which part of the codebase is getting the most benefits from the Go optimizations.

Or maybe you just wanna play around with how Go works at a lower level 🤷😉

Shuffle the sequence of running your tests

Sometimes, engineers don’t write independent unit tests. The tests successfully pass because they rely on a particular order of execution.

If you want to make your tests more independent and code more reliable, use -shuffle to run your tests. Note that this flag was introduced from Go v1.17 onwards.

Output from Go docs for the -shuffle flag

Detect race conditions at runtime in go code

The --race flag used as go run --race main.go helps in detecting race conditions in your go code.

This blogpost by Uber is an amazing example of how they leveraged this flag to remove race conditions from their codebases.

Print the optimization decisions taken by the Go compiler

gcflags="-m” used as go build -gcflags="-m" main.go will show you the compilation decisions taken by Golang compiler

package main

import "fmt"

func add(a, b int) int {
	return a + b
}

func main() {
	x := 2
	y := 3
	fmt.Print(add(x, y))
}

Shows output of a go build command with the -m gcflag

Got any other interesting Go flag? DM me on twitter @shivam_310 or email me at shivamsinghal5432 [AT] gmail [DOT] com