Conditional compilation in Go

Masato Nakamura
1 min readMay 9, 2018

--

We often want to change method behavior in each environment such as production or staging.

Go supports conditional compilation with build tool options.

Build Constraints

As an example, There are these files in a repository.

debug.go

// +build debugpackage mainimport (
"log"
"time"
)
func Now() {
log.Print("debug mode")
log.Print(time.Now())
}

release.go

// +build !debugpackage mainimport (
"log"
"time"
)
func Now() {
log.Print(time.Now())
}

main.go

package mainfunc main() {
Now()
}

Go has -tags build options. This option reacts to the magic comment // +buildwhich are the top of source files.

When building source files, we can specify tags of which file to build.

$ go build
$ ./app
2018/05/09 21:51:51 2018-05-09 21:51:51.418615533 +0900 JST m=+0.000285531
$ go build -tags debug
$ ./app
2018/05/09 21:51:51 debug mode
2018/05/09 21:51:51 2018-05-09 21:51:51.418615533 +0900 JST m=+0.000285531

By using -tags build options, We can switch any values or method behavior in each environment.

--

--

Masato Nakamura

Backend Engineer at Toreta. Cityscape Photographer. #ruby #golang #kubernetes