Skip to content

How to compile and run a Go program

This tutorial continues what we did in how to create your first Go program.

Open a terminal in the hello folder and run the program using

go run hello.go

Screen Shot 2022-07-28 at 12.18.23.png

Our program ran successfully, and it printed “Hello, World!” to the terminal!

The go run tool first compiles and then runs the program specified.

You can create a binary using go build:

go build hello.go

This will create a hello file that’s a binary you can execute:

Screen Shot 2022-07-28 at 12.19.50.png

In the introduction I mentioned Go is portable.

Now you can distribute this binary and everyone can run the program as-is, because the binary is already packaged for execution.

The program will run on the same architecture we built it on.

We can create a different binary for a different architecture using the GOOS and GOARCH environment variables, like this:

GOOS=windows GOARCH=amd64 go build hello.go

This will create a hello.exe executable for 64-bit Windows machines:

Screen Shot 2022-07-28 at 15.36.55.png

Setup for 64-bit macOS (Intel or Apple Silicon) is GOOS=darwin GOARCH=amd64 and Linux is GOOS=linux GOARCH=amd64.

This is one of the best features of Go.


→ Get my Go Handbook

download all my books for free

  • javascript handbook
  • typescript handbook
  • css handbook
  • node.js handbook
  • astro handbook
  • html handbook
  • next.js pages router handbook
  • alpine.js handbook
  • htmx handbook
  • react handbook
  • sql handbook
  • git cheat sheet
  • laravel handbook
  • express handbook
  • swift handbook
  • go handbook
  • php handbook
  • python handbook
  • cli handbook
  • c handbook

subscribe to my newsletter to get them

Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing flavio@flaviocopes.com. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.

Related posts about go: