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.
Getting ready
Install and verify the Go installation. The following steps could help:
- Download and install Go on your machine.
- Verify that your
GOPATH
andGOROOT
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.
How to do it...
The following steps cover the solution:
- Open the console and create the folder
chapter01/recipe01
. - Navigate to the directory.
- Create the
main.go
file with the following content:
package main import ( "log" "runtime" ) const info = ` Application %s starting. The binary was build by GO: %s` func main() { log.Printf(info, "Example", runtime.Version()) }
- Run the code by executing the
go run main.go
. - See the output in the Terminal:

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.