Compile Go programs

Compile Go source code into executables and libraries on Red Hat Enterprise Linux with the Go compiler in Go Toolset by using a Red Hat-supported toolchain for building command-line tools, services, and shared libraries.

Prerequisites

  • Go Toolset is installed.

Configure a Go workspace

Modern Go projects are built using modules. You can start with a single module and then optionally group multiple modules into a workspace to work on them simultaneously.

Procedure

  1. Create a root directory for your projects, for example:
    $ mkdir ~/go-projects/
  2. Change into the project directory:
    $ cd ~/go-projects/
  3. Initialize a module:
    1. Create a directory for your module:
      $ mkdir <module_name>
    2. Change into the module’s directory:
      $ cd <module_name>
    3. Initialize the module:
      $ go mod init <module_name>

      This command creates a single-module project.

    If you want to create multiple modules, repeat this step for every module.

  4. If you want to work on multiple modules at the same time, create a multi-module workspace:
    1. Change into the project directory:
      $ cd ~/go-projects/
    2. Initialize a workspace to include multiple modules:
      $ go work init <module_name_1><module_name_n> ...

Compile a Go program

You can compile Go sources in the current directory by running go build to produce an executable binary.

Before you begin

  • A Go workspace with configured modules.

Procedure

Compile the Go sources in the current directory:
$ go build .

Run a Go program

The Go compiler creates an executable binary file as a result of compiling. Complete the following steps to run your program.

Procedure

Use one of the following options to run your Go program:
  • To run a compiled Go program, enter:
    $ ./<file_name>

    Replace <file_name> with the name of your executable file.

  • To compile the Go sources in the current directory and run the program in a single step, enter:
    $ go run .

Install compiled Go projects

You can download and install third-party Go projects from online resources to use their executable files and libraries in further Go projects. After installation, Go copies the project’s executables and libraries to workspace directories and installs its dependencies as well.

Before you begin

  • A Go workspace with configured modules.

Procedure

Install a Go project:
$ go install <go_project>

Download and install Go projects

Use go install with a third-party import path to download and install Go commands and libraries into your workspace. Optionally, run go help importpath for details on how to specify remote projects.

Before you begin

  • A Go workspace with configured modules.

Procedure

  1. To download and install a Go project, enter:
    $ go install <third_party_go_project>
  2. Optional: For information on possible values of third-party projects, enter:
    $ go help importpath