Retrieving the Golang version

While building a program, it is a good practice to log the environment settings, build version, and runtime version, especially if your application is more complex. This helps you to analyze the problem, in case something goes wrong.

Besides the build version and, for example, the environmental variables, the Go version by which the binary was compiled could be included in the log. The following recipe will show you how to include the Go runtime version into such program information.

  • Download and install Go on your machine.
  • Verify that your GOPATH and GOROOT environmental variables are set properly.
  • Open your Terminal and execute go version. If you get output with a version name, then Go is installed properly.
  • Create a repository in the GOPATH/src folder.
package main

import (

const info = `
			 Application %s starting.
			 The binary was build by GO: %s`

func main() {
	log.Printf(info, "Example", runtime.Version())


Biradars-MacBook-Air-4:golang-daily sangam$ go run main.go 
2019/11/30 01:53:12 
			 Application Example starting.
			 The binary was build by GO: go1.13.4

  • How it works…

  • The runtime package contains a lot of useful functions. To find out the Go runtime version, the Version function could be used. The documentation states that the function returns the hash of the commit, and the date or tag at the time of the binary build.

  • The Version function, in fact, returns the runtime/internal/sys .The Version constant. The constant itself is located in the $GOROOT/src/runtime/internal/sys/zversion.go file.

  • This .go file is generated by the go dist tool and the version is resolved by the findgoversion function in the go/src/cmd/dist/build.go file, as explained next.

  • The $GOROOT/VERSION takes priority. If the file is empty or does not exist, the $GOROOT/VERSION.cache file is used. If the $GOROOT/VERSION.cache is also not found, the tool tries to resolve the version by using the Git information, but in this case, you need to initialize the Git repository for the Go source.