In this tutorial, we will build upon what we learned in our previous tutorial on how to create your first Go program. If you haven’t read it yet, you can find it here.
To compile and run a Go program, follow these steps:
- Open a terminal in the
hello
folder where your Go program is located. - Use the
go run
command to compile and run the program. Enter the following command in the terminal:
go run hello.go
- The program will be compiled and executed. If everything goes well, you should see the output “Hello, World!” in the terminal.
By using the go run
command, Go first compiles the program and then runs it.
If you want to create a binary executable of your Go program, you can use the go build
command instead. This allows you to distribute the program to others who can run it without installing Go.
To create a binary executable, follow these steps:
- Open a terminal in the
hello
folder. - Use the
go build
command followed by the name of your Go program file. Enter the following command in the terminal:
go build hello.go
- A binary file named
hello
will be created. This file is the executable version of your Go program.
Now, you can distribute this binary file to others, and they can run it directly without having Go installed on their machines. The binary is already packaged for execution.
The binary will run on the same architecture it was built on. However, if you want to create a binary for a different architecture, you can use the GOOS
and GOARCH
environment variables.
For example, to create a binary executable for 64-bit Windows machines, use the following command:
GOOS=windows GOARCH=amd64 go build hello.go
This will create a hello.exe
executable.
Similarly, to create a binary for 64-bit macOS (Intel or Apple Silicon), use GOOS=darwin GOARCH=amd64
. For Linux, use GOOS=linux GOARCH=amd64
.
This flexibility to create binaries for different architectures is one of the great features of Go.