Setup · 03
03. Your first Go program
Compile and run a one-file Go program with go run, then create an executable program.
To create a Go program, make a directory and create one file named main.go. Add the following code to the file and save it:
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
Every executable Go program starts with package main and a func main(). Go comes with a “standard library” that provides many useful packages, including fmt for formatted output. To format output, you first have to import that package.
Run your program directly with go run:
$ go run main.go
Hello, World!
go run compiles to a temporary binary file, runs it, and discards it. For a real binary, use go build:
$ go build -o hello main.go
$ ./hello
Hello, World!
The -o flag specifies the output filename for the compiled program. So the -o hello part of the command tells the computer to create an executable file named hello.
The output is a single static binary file. You can give the compiled hello file to anyone with the same OS and CPU even if they don’t have Go installed, and they will be able to run it.