DEV Community

Cover image for [Go Tour] 1. Exploring the `go build` Command
Thao Nguyen
Thao Nguyen

Posted on • Edited on

[Go Tour] 1. Exploring the `go build` Command

First execution of go build

Let's start with a basic Go application
basic golang application
in the go build command, you can use the -v option to display the names of packages as they are compiled:
CGO_ENABLED=0 go build -v -o /tmp/basic-svc ./

$ CGO_ENABLED=0 go build -v -o /tmp/basic-svc ./
go: downloading gorm.io/gorm v1.25.5
go: downloading gorm.io/driver/sqlite v1.5.4
go: downloading github.com/mattn/go-sqlite3 v1.14.18
go: downloading github.com/jinzhu/now v1.1.5
go: downloading github.com/jinzhu/inflection v1.0.0
internal/goexperiment
internal/godebugs
internal/unsafeheader
internal/coverage/rtcov
internal/goarch
internal/goos
unicode/utf8
math/bits
internal/cpu
runtime/internal/atomic
internal/itoa
runtime/internal/syscall
internal/race
sync/atomic
unicode
encoding
unicode/utf16
internal/abi
runtime/internal/math
runtime/internal/sys
crypto/internal/alias
crypto/subtle
crypto/internal/boring/sig
strings
....
Enter fullscreen mode Exit fullscreen mode

Upon the first execution of go build, some packages are downloaded from internet. And a bunch of package, including many Go standard libraries are compiled.

Caching in go build

The downloaded packages are stored in ~/go/pkg/mod/*, and the compiled binaries generated by go build reside in ~/.cache/go-build/*. Keeping the source code unchanged, and execute the go build command again, no packages are recompiled as it efficiently utilizes the cache.

$ CGO_ENABLED=0 go build -v ./
$ 
$ 
Enter fullscreen mode Exit fullscreen mode

Compilation of Dependencies

In this example, the dependency hierarchy: the main imports the service, the service imports the repository.
When changes are made to the repository package, executing go build subsequently triggers recompilation of three packages:

$ CGO_ENABLED=0 go build -v -o /tmp/basic-svc ./
openlab1/basic-svc/internal/repository
openlab1/basic-svc/internal/service
openlab1/basic-svc
Enter fullscreen mode Exit fullscreen mode

Key Takeaways:

  • Go builder detects which packages need to be re-compiled. It avoid unnecessary recompilation.
  • During the first execution of go build, all the necessary packages are downloaded (if they do not exist) and subsequently compiled.
  • This feature can be leveraged to optimize a Dockerfile specifically for a Golang application (details in the next post)
  • Maintaining small and independent Go packages helps prevent unnecessary recompilations. (details in the next post)

Top comments (0)